C code for ignoring the enter key after input

2019-05-20 08:03发布

I am having a problem with the Enter key or character in the stdin stream messing up following input calls.

let's say I have one input call, so I enter in the stuff. but then takes the Enter key as input for the next input call.

I think in c++ there is cin.ignore() to do the trick.

I just can't find the C version.

The input methods are getchar() and gets().

Sorry if this is a duplicate. I couldn't find the question that matches mine. thanks for any help!

        printf("Do you want to view the lines? ");
    int choice = getchar();
    while (choice == 'y')
    {
            char line[80];
            printf("What line do you want to see? ");
            gets(line);
            if (line != "all")
            {
                    n = atoi(line);
                    printf("Line %d: %s\n",n,list[n]);
            }
            else
                    for (int i = 0; i<size; i++)
                            printf("%s \n",list[i]);
            printf("Any more lines? ");
            choice = getchar();
    }

I admit that this is extremely basic, but still learning .

1条回答
来,给爷笑一个
2楼-- · 2019-05-20 08:25

You simply need to keep calling getchar to consume the characters you don't want from the stream. If you know there's always a single additional character then it is as simple as making one additional call to getchar.

If you want to remove multiple characters from the stream or deal with situations where the input may actually contain something you really need you can do something like the code below instead of your choice = getchar().

do
{
  choice = getchar();
} while(choice=='\n'); // Add any other characters you may want to skip

This will keep removing characters (in this case only if they are newline) but leave choice set to the first non-removed character.

By the way, you can't compare strings like that (!= "all") use the C string compare functions, e.g. strcmp().

More generically the C++ istream ignore can be roughly written in C as something like the code below; call with stdin to skip characters from the standard input:

int ignore(FILE *stream, int n, int delim)
{
  int c;
  while(n>0)
  {
    c = getc(stream);
    if(c==EOF || c==delim)
    {
      return c;
    }
    n--;
  }
  return(c);
} 
查看更多
登录 后发表回答