输入后忽略回车键的C代码 [英] C code for ignoring the enter key after input

查看:48
本文介绍了输入后忽略回车键的C代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在输入调用之后,stdin 流中的 Enter 键或字符出现问题.

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

假设我有一个输入调用,所以我输入了内容.但随后将 Enter 键作为下一个输入调用的输入.

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.

我认为在 C++ 中有 cin.ignore() 可以做到这一点.

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

我就是找不到 C 版本.

I just can't find the C version.

输入方法是getchar()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 .

推荐答案

您只需要不断调用 getchar 来使用流中不需要的字符.如果您知道总是有一个额外的字符,那么它就像对 getchar 进行一次额外调用一样简单.

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.

如果您想从流中删除多个字符或处理输入实际上可能包含您真正需要的内容的情况,您可以执行以下代码而不是您的 choice = 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.

顺便说一句,您不能使用 C 字符串比较函数来比较这样的字符串 (!= "all"),例如strcmp().

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

更一般地,C++ istream ignore 可以粗略地用 C 编写,类似于下面的代码;使用 stdin 调用以跳过标准输入中的字符:

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

这篇关于输入后忽略回车键的C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆