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
3 Réponses
+ 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
+ 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...
+ 1
Yahel,
Please share the code link so we can colaborate further on this issue.