| mborja (9) | |||
Safer alternative to scanf() for reading user input as strings:
| |||
|
Last edited on
|
|||
| jsmith (5804) | |
|
But also useless, since the user can't use BACKSPACE to fix typos. string s; getline( cin, s ); done. | |
|
|
|
| mborja (9) | ||
/me needs no BACKSPACE :-) Perhaps it's Cygwin or my compiler platform, but I don't find any problems backspacing to correct typos on the command line where input is accept. I can type: asdf ...backspace once and type: asd1 ...and it's read without any problems into my input array of characters. Perhaps a better explanation is in order about why the user can't use a backspace? | ||
|
Last edited on
|
||
| jsmith (5804) | |
|
Because your input buffer looks like a s d f \8 1 when that gets printed, it looks like asd1 because the terminal honors the backspace. print out strlen( input ) or do strcmp( input, "asd1" ) when you type asdf <bs> 1 and you'll see the length is 6 and the strings are not equal. | |
|
|
|
| mborja (9) | |||
printf("%s (size: %d)\n", input, strlen(input));When run:
By the way, have you actually compiled this program for yourself? At any rate, still not seeing the problem. | |||
|
Last edited on
|
|||
| jsmith (5804) | |
|
Ah, it's because getchar() doesn't actually return until the user presses ENTER so the input is being pre-processed before it gets to the program. | |
|
|
|
| jsmith (5804) | |||||
Actually, though, now that I think about it,
does the same thing as your code, except it does not have the arbitrary input buffer size limitation. Though %as is not standard, IIRC. Anyways being a C++ forum, I'd use streams instead. Here's a little function I cobbled up that is not only buffer overflow-proof, but also handles entry of any type so long as it is streamable:
| |||||
|
|
|||||