0

好的,所以我在我的教科书中遇到了这个代码片段,它应该与用户输入的每个其他字符相呼应。现在,我理解了所有其他字符部分,但我在使用 cin.get() 时遇到了困难。我明白为什么第一个 cin.get() 在那里,但为什么它也在循环内?我猜我没有完全掌握输入流的性质......

编辑:它刚刚点击...我是个白痴。感谢您清除它。

char next;
int count = 0;
cout << "Enter a line of input:\n";
cin.get(next);

while (next != '\n')
{     
    if ((count%2) == 0)
    cout << next;
    count++;
    cin.get(next);
}

提前致谢!

4

6 回答 6

3

cin.get在这种情况下,不会像您所相信的那样“抓住一行文字”。cin.get在这种情况下,只抓取一个字符。随着cin.get您阅读用户正在输入的字符,一个接一个,一个接一个。这就是为什么你有cin.get一个循环。

于 2009-10-18T08:26:57.383 回答
1

在循环之前对 cin.get(next) 的调用只是将缓冲的用户输入的第一个字符放入变量“next”中。

一旦进入循环,并且存储在 'next' 中的字符已被处理(如果在偶数索引处回显,否则将被忽略),需要再次调用 cin.get(next) 以检索下一个字符。

于 2009-10-18T08:25:18.950 回答
1

它的印刷字符出现在均匀的位置

char next;
int count = 0;
cout << "Enter a line of input:\n";
cin.get(next);//gets first character (position zero) from input stream

while (next != '\n')//check whether the character is not line feed(End of the line)
{     
    if ((count%2) == 0)//checks if position is even
    cout << next;      //if yes print that letter
    count++;           //increments the count
    cin.get(next);     //gets next character from input stream
}

我们需要两个cin.get(...)

  • 在进入 while 循环之前,我们需要知道第一个字符(位置零)
  • 在while循环中获取下一个字符
于 2009-10-18T08:25:51.177 回答
1

但是 cin.get(ch) 外部的用途是什么 它有什么作用(下一个)但它不会打印它......它会在按下回车键后一起打印......实际上它应该在我们从键盘键入时显示字符,但它实际上并没有像那样工作

于 2010-09-23T15:05:07.947 回答
0

C++ 中的流是缓冲的。把它们想象成一行字母。当您调用cin.get(var)该行中的第一个字符时,将删除并返回给您。所以,这就是它的工作原理。

一个例子会更好。执行第一个 cin.get() 时,假设您输入 :
LISP
然后 cin.get() 将返回(在 var. 中)L,然后缓冲区看起来像ISP......下一次调用将I放在变种。缓冲区看起来像SP等等......

于 2009-10-18T08:19:18.043 回答
0

istream& get(char &c) 从输入流中获取一个字符。

所以在第一次调用 cin.get(next) 时,你输入:“hello world!” 然后未来的 cin.get(next) 将在每次调用时获取 h、e、l、l 等......直到输入流中没有更多字符,这时它将阻止向用户询问更多输入。

于 2009-10-18T08:22:37.180 回答