What does scanf do to the value it reads? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

What does scanf do to the value it reads?

Picture this: single variable, and scanf is set to expect a value of type int. What happens internally when, say, a character is entered? Does scanf just ignore it, or run a check on whether its a number - how does it know?

9th Jun 2019, 1:12 PM
Maksim Leon
Maksim  Leon - avatar
1 Antwort
+ 4
A lot can go wrong when reading from stdin, check the "Return Value" section in the cplusplus docs: http://www.cplusplus.com/reference/cstdio/scanf/ We have the feof and ferror functions, checking the return value for EOF, checking the errno variable for EILSEQ. It's a can of worms. Anyway in your case: Nothing will be read. `scanf` will tell you how many characters it read, so you can check that for 0. int a = 1234; int n = scanf("%d", &a); if(n == 0) { printf("You did an oopsie!\n."); // a is still 1234 here, it wasn't touched } And yes, scanf runs checks - if you check the docs I linked above you can see which format specifier allows which inputs exactly!
9th Jun 2019, 1:54 PM
Schindlabua
Schindlabua - avatar