what happens when you input things like 12ab to scanf(“%d”,&argu)?

前端 未结 5 1911
无人共我
无人共我 2020-12-11 07:08

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 wro

5条回答
  •  既然无缘
    2020-12-11 07:37

    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. */
    }
    

提交回复
热议问题