Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

c - what happens when you input things like 12ab to scanf("%d",&argu)?

I came across this problem when I want to check what I input is number. The scanf function will return 1 if I successfully input a number. So here is what I wrote:

int argu;
while(scanf("%d",&argu)!=1){
    printf("Please input a number!
");
}

But when I input things like abcd to it, the loop would go forever and not stop for prompt.

I looked it up online and found that it had something to do with the cache and I need to clean it up so scanf can get new data. So I tried fflush but it didn't work.

Then I saw this:

int argu,j;
while(scanf("%d",&argu)!=1){
    printf("Please input a number!
");
    while((j=getchar())!='
' && j != '
');
}

Then when I input things like 'abcd' it worked well and it prompted for my input. But when I input things like '12ab', it wouldn't work again.

So is there a way I can check the input for scanf("%d", &argu) is actually a number and prompt for another input if it isn't?

EDIT:

I saw the answers and solved my problem by using while(*eptr != ' ').

Notice that the fgets function actually reads ' ' into the array and gets doesn't. So be careful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's better to read a full line, using fgets(), and then inspecting it, rather than trying to parse "on the fly" from the input stream.

It's easier to ignore non-valid input, that way.

Use fgets() and then just strtol() to convert to a number, it will make it easy to see if there is trailing data after the number.

For instance:

char line[128];

while(fgets(line, sizeof line, stdin) != NULL)
{
   char *eptr = NULL;
   long v = strtol(line, &eptr, 10);
   if(eptr == NULL || !isspace(*eptr))
   {
     printf("Invalid input: %s", line);
     continue;
   }
   /* Put desired processing code here. */
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...