In C, Strings are just array of char type of variables. So,
char myString[100]
This will be handled by the compiler as a string of 99 characters and the last one 'should' be null. Null in C is defined as '\0'. If you read the characters by using scanf, then it wont put the terminating character(\0) at the end. So, rather use fgets.
Suppose, you are reading a string of 50 characters using scanf, then you can terminate the end by using the following statement
myString[50] = '\0';
try the sample code
#include <stdio.h>
int main()
{
char myString[50];
fgets(myString, 49, stdin);
printf("%s\n",myString);
return 0;
}
That's the most convenient way to read a String and get an output iin C. fgets always puts the terminating character (\0) automatically at the end of the string.
I need to clear the buffer or reset the string to 0 (empty).
char string [100];
User enter a string, I do something with it, done. Reset to 0. If the string is not reset, when user enter new string, the code keeps working with the old string instead of new one.
The problem is that you are setting the 101st character (which is really not a good idea since you have 0-99 available) = to the '\0' character.
You want to set the first character to the '\0' character...so
char string[100];
string[0]='\0';
So if you use prinf("The string is %s\n", string);
It will print nothing for the %s.
Now, remove that second line and try to run it again. You will most likely get garbage.
Another way to clear it would be to use memset and set the string to all zeros, but that is not really needed here, nor is it really the proper thing to do. You can intitialize a string like this in the same fashion.
char string[100] = {0};
Remember, all a char array really is a is a bunch of characters starting at a some point in memory. All of the standard string functions need to know where the string ends so it uses a '\0' character to represent this. You could write all of your own string processing functions and use the letter x to represent the end of the string, but that wouldn't be very useful then. And remember, you shouldn't use the 100th index in a 100 character array. It starts at 0 and goes to 99.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.