How can i get String input in C? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can i get String input in C?

How to get string input in C using scanf() function?

30th Jul 2020, 11:25 AM
Yogeshwaran P
Yogeshwaran P - avatar
7 Answers
+ 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/
30th Jul 2020, 1:48 PM
Ipang
+ 2
Thanks you all for yours guidance:)
30th Jul 2020, 1:51 PM
Yogeshwaran P
Yogeshwaran P - avatar
+ 1
codemonkey can you give me example for getting user string input by using scanf () function?
30th Jul 2020, 11:33 AM
Yogeshwaran P
Yogeshwaran P - avatar
+ 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
30th Jul 2020, 11:44 AM
Yogeshwaran P
Yogeshwaran P - avatar
+ 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
30th Jul 2020, 11:50 AM
Yogeshwaran P
Yogeshwaran P - avatar
+ 1
scanf or gets or getchar
31st Jul 2020, 3:16 PM
Sanjay Kamath
Sanjay Kamath - avatar
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..
30th Jul 2020, 12:17 PM
Jayakrishna 🇮🇳