String Input - C | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

String Input - C

Hello, assume I'm taking a String user-input and I define the char array like so: char str[5]; this way i'm expecting just 5 chars. when i enter input that is more than 5 chars it still works and the program doesn't crash due to buffer overflow. Why don't I get an error? code: char str[5]; scanf("%s", str); printf("%s", str); input: abcdefg1234 output: abcdefg1234

30th Oct 2022, 4:45 PM
Yahel
Yahel - avatar
3 Answers
+ 2
We can limit number of byte read by specifying the width sub-specfier, for example char str[ 6 ]; // 5 characters + 1 for string terminator scanf( "%5s", str ); // limit the reading up to 5 bytes + Look for "width" sub-specifier on this page http://www.cplusplus.com/reference/cstdio/scanf/ Yahel
30th Oct 2022, 4:50 PM
Ipang
+ 1
Ipang, assume i have another scanf below that scanf and i enter more than 5 chars. what happens is that the excess chars entered are slipping through and getting into the next scanf's. what can i do to prevent that? i thought i needed to flush the buffer but i dont think it worked...
1st Nov 2022, 11:36 AM
Yahel
Yahel - avatar
+ 1
Yahel, Please share the code link so we can colaborate further on this issue.
3rd Nov 2022, 7:01 AM
Ipang