C code for ignoring the enter key after input

断了今生、忘了曾经 提交于 2019-12-22 12:39:08

问题


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:


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);
} 


来源:https://stackoverflow.com/questions/14681020/c-code-for-ignoring-the-enter-key-after-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!