+ 1
How can i get String input in C?
How to get string input in C using scanf() function?
8 Réponses
+ 4
Yogeshwaran
You can adjust how many characters are allowed to be read into the string buffer by adjusting the width sub-specifier
char buffer[10]; // length 10
scanf("%9s", buffer); // %9s -> read 9 chars max, type is string
// spare the last char for string terminator
puts(buffer);
About sub-specifier, check this one 👇
http://www.cplusplus.com/reference/cstdio/scanf/
+ 2
Thanks you all for yours guidance:)
+ 1
codemonkey can you give me example for getting user string input by using scanf () function?
+ 1
codemonkey what is the use of putting 42 inside the array index?
can we put 0 inside the array index.Both are showing same results only
+ 1
codemonkey thanks :)
But
I ask this question because this code behaviour was closely related to gets() function [buffer overflow]
Please clarify me
Because it(scanf()) also don't bother about char array limit
+ 1
scanf or gets or getchar
0
Yogeshwaran
If you declare char array in c like char arr[20]. You can only 20 charecters, index start from 0 to 19(max). Anything beyond this access, then you may get different values in different times, garbage values..
For your previous question answer, if you use gets, then if you access beyond array length, then values get replaced from start and you get undesired behavior.. So it's not recommended to use gets and it is deprecated from standards also... Use fgets instead...
If you use 0 size, then it's no use.. Infact it is error..
you may store values if you use size atleast 1 but you may not get same values when you retrieve it... So add the required size before hand.. Hope it helps..