Thursday, July 30, 2009

Does anyone know how to write a string in C?

#include %26lt;stdio.h%26gt;





int main(void)


{


char[] = "Happy birthday";


return 0;


}

Does anyone know how to write a string in C?
Your question is somewhat vague. Write a string to where, a file? The screen? An array?





The standard way to write a string in C would be to call the printf function:


printf("Hello, world.");


This will output the string "Hello, world." (without the quotes) to the device currently assigned to stdout (i.e., standard out, usually the screen).
Reply:1) Declare an array of characters. Make sure they are initialised to 0 so there are no garbage values in there. The array of characters should be large enough to store the string required.





char string_space[50] = {0};





string_space is just an array of characters. It needs to be filled with characters which will form the string. All strings end in the null character '\0' so you need to use proper C string functions, which automatically add it, or make sure you add it yourself.





2) Use sprintf() to fill the contents of the string as you would use printf() to print to the screen





sprintf(string_space, "abcdefgh");





sprintf() will append the terminating null character '\0' at the end the string_space to make it a proper string.





string_space = a b c d e f g h \0 * * .... * * (until 50)





3) If you want to see the contents of the string on a screen you may then use printf().





printf("%s", string_space);
Reply:Yeah I know how: a string in C? There, I wrote it. Happy? You need to be more specific when asking a question, silly! I still don't get what you meant. It sounded like a possible music thing, but IDK!


No comments:

Post a Comment