1

这段代码是用 C++ 编写的,由于我不太明白的原因,它被编写了两次。我希望在输入一个随机字符后,它会显示一次字符,而字符串也会显示一次。但我没有把它作为输出。我错过了什么?

解决方案:添加 cin.ignore() 语句也会忽略读入的返回。让我的代码循环一次。

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
    char letter;

    letter = cin.get();
    while (letter!= 'X')
    {
        cout << letter << endl;
        cout << "this will be written twice for ununderstandable reasons";                
        letter = cin.get();
    }
}

示例:如果我用 cmd scrn 写c,我会得到一个cback + 两次短语this will be written twice for ununderstandable reasons。所以我认为是输出

c
this will be written twice for ununderstandable reasons

实际上是

c
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
4

6 回答 6

2

你忘记了换行符。cin 读取每个字符,其中包括您在键入字符后键入的换行符。如果您不想要这种行为,则必须专门检查换行符。

while (letter!= 'X')
{
      if (letter == '\n')
      {
          letter = cin.get();
          continue;
      }
      cout<<letter<<endl;
      cout<<"this will be written twice for ununderstandable reasons";
      letter= cin.get();
}
于 2013-11-05T11:54:28.483 回答
2

您正在使用未格式化的get()函数读取每个字符,包括每次按回车键时的换行符。

根据您要执行的操作,您可以使用格式化输入 ( cin >> c) 来跳过所有空格;或者您可以测试每个字符并忽略您不感兴趣的换行符之类的内容;或者你可以用它getline(cin, some_string)来阅读整行,然后处理它。

于 2013-11-05T11:56:11.633 回答
2

当您输入一个字符时,换行符(按回车键)也在您的输入缓冲区中。

来自 C 参考:

如果找到分隔符,则不会从输入序列中提取,而是保留在那里作为要从流中提取的下一个字符(有关丢弃分隔符的替代方法,请参见 getline)。

只需使用 a cin.sync()after everycin.get()来清除缓冲区,就可以了。

于 2013-11-05T11:59:08.943 回答
2

正如每个人已经提到的,每次您按回车键时cin都会附加换行符。\n另一种解决方案是cin.ignore();在每个cin.get();.

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
    char letter;

    letter = cin.get();
    cin.ignore();
    while (letter!= 'X')
    {
          cout<<letter<<endl;
          cout<<"this will be written twice for ununderstandable reasons";
          letter= cin.get();
          cin.ignore();
          }
}
于 2013-11-05T12:01:31.193 回答
2

文本“这将被写入两次..”不一定会打印两次。

键入 'qwerty' + ENTER ,您的流中将包含“qwerty\n”,您将看到以下输出:

this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons

与字符串 "qwerty\n" 一样多的字符。问题是

cin.get()

将您输入的所有字符放入流/缓冲区(不是您的字母字符),但每次 cin.get() 调用处理一个字符。

当您输入“abcXd”+回车时,程序将在行上方打印 3 次并在 X 处停止。

于 2013-11-05T12:11:09.043 回答
1

发生这种情况是因为 cin.get()new-line也读取字符。尝试在Enter没有任何符号的情况下按下或键入一些字符串,例如abc. 你需要处理它,例如:

while (letter = cin.get()) {
    if (!isalpha(letter)) { continue; }
    // handling user inputted alpha
}
于 2013-11-05T12:06:39.477 回答