how to take user input stringand store it in array
how to take user input stringand store it in array
You did say 'string' which means it's nul terminated. You must ensure that the destination is large enough.Code:char storage[100]; ... strcpy(storage, userinput);
For user's input, (where errors are likely):
char inputstr[80];
fgets(inputstr, sizeof(inputstr), stdin);
The newline: '\n', and end of string char: '\0', will automatically be added to the end of the string array, by fgets(). (space permitting).
Early chapters of C books for beginners, will usually use
scanf("%s", inputstr);
scanf() will append the end of string char, and will NOT add the newline char to the string.
The big advantage of fgets() is that the user can't add too many char's, into the receiving char array.
You can also use the width parameter of scanf() to enforce the size limitation.
But one of the problems with scanf(), compared to fgets() is that scanf() stops processing when it encounters a space, fgets() doesn't stop until it encounters the end of line character.Code:char s[100] scanf ("%100s",str);
Jim