Reputation: 397
I wrote this test program to get the return value of the scanf() function.
however in the test, if i input a integer, the program is normal, but when i input a string, it will go into a endless loop. who can explain the reason for that?
another thing is that is the escape character \0 stand for the ascii code 0? when I print a "\12", i will get a new line, but when I print "\9", I couldn't get a "TAB"(the TAB's ascii code is 9).
#include <stdio.h>
int main(void){
int x;
int temp;
//printf("\13");
for(;;){
temp=scanf("%d",&x);
printf("%i",temp);
}
}
Upvotes: 2
Views: 180
Reputation: 2881
When scanf
cannot read what you ask in the format string, it just leaves data in the input stream, and the next time it will read it again, failing again, and so on, for ever. You should empty your input.
Also, you should not rely on ASCII, according to the standard. But yes, '\0'
is the null character, and you should use '\t'
instead of the hardcoded ASCII value.
Upvotes: 3
Reputation: 23268
You're telling scanf
to read an integer. If you input a string the scanf
will wait for an integer input. scanf
also does not purge the input so it will read the same thing over and over again. You should check the value of temp
when it successfully read something it will return the count of successful reads. In your case on the string input it should return 0.
Also depending on where you output and the shell you use the tab output may or may not be ignored or interpreted differently.
Upvotes: 3
Reputation: 121347
When the input doesn't match the format specifier, scanf() doesn't discard the input which causes the infinite loop.
for(;;){
temp=scanf("%d",&x);
if(temp == 0) { // Input failure
perror("invalid input");
break;
}
printf("%i",temp);
}
If you still want to continue the loop even after invalid input, you have read the input and flush it yourself.
Upvotes: 4