See the FAQ for flusing the input buffer then, http://faq.cprogramming.com/cgi-bin/...&id=1043284392
Printable View
See the FAQ for flusing the input buffer then, http://faq.cprogramming.com/cgi-bin/...&id=1043284392
You have to understand that user input is kept in a buffer called stdin. It is dynamic and resizes itself so you don't have to worry about making things fit into it. When you store 20 bytes (characters) of data into an array you are using a function to read 20 bytes from stdin and store them into the array. If you don't tell it to read 20 bytes (if you use a function like scanf() where the array size is not passed to the function, it will read bytes from stdin until it encounters a NULL or a byte represented in hex as 00 meaning the end of the string). If you understood nothing I just said, just remember to use fgets and specify the length of your array and you will never run into problems concerning overflow.
1) The data is read from a stream, not a buffer. A buffer may be in there, but it is irrelevant to the concept of reading from a stream.
2) You can tell scanf() the buffer size:
It even works for dynamically sized buffers:Code:scanf("%20s", buffer);
3) The limit character for fgets() is the newline, '\n', not the NUL. A text stream will in fact never emit a NUL; at best it will emit an EOF.Code:scanf("%*s", size, buffer);
Oh, sorry. In that case, you have to create a format string.
Stupid omission, IMO.Code:sprintf(buffer1, "%%%is", size);
scanf(buffer1, buffer2);
So how big do you make buffer1? [/nitpick]
Very ugly. I never said it was nice, only that it was possible.
jus a quick question. Is there a command to erase the buffer in C. say i enter a string. now i can say if string>20 then erase buffer and reinput?
You mean like this FAQ question:
http://faq.cprogramming.com/cgi-bin/...&id=1043284392
--
Mats
ya i was doing the buffer thing: scanf("%20s", buffer);
but once i enter more than 20 characters i get a segmentation fault. How can i create an error message instead?
Yes, becasue scanf is "stupid" and can't deal with things going wrong very well - there is A REASON we suggest using fgets() instead - it is more fault-tolerant and unless you do things wrong, you can't make it overwrite other variables and such.
But unfortunately, you are in a class where you can't use that [unless I'm confused], so you have to live with the application not being particularly fault-tolerant.
--
Mats