使用while(cin> x) [英] Using while(cin>>x)

查看:103
本文介绍了使用while(cin> x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C ++ cin空格问题

我在尝试理解问题这段代码。如果这个问题已经得到解答,但我在任何地方都找不到,我很抱歉。我是一个初学者,它是非常基本的代码。问题是>> 运算符会在遇到第一个空格
字符时停止读取,但是为什么在这种情况下即使我们的字符串中有空格,它也会输出完整的输入字符串。它在单独的行中输出字符串的每个单词。 cin >> x 即使在空格后也能接受输入呢?请帮我解决这段代码的功能。

I'm having problem trying to understand this piece of code. I'd like to apologize if this question has already been answered but I didn't find it anywhere. I'm a beginner and its a very basic code. The problem is >> operator stops reading when the first white space character is encountered but why is it in this case it outputs the complete input string even if we have white spaces in our string. It outputs every word of the string in separate lines. How is it that cin>>x can take input even after the white space? Plz help me out with the functioning of this code. Thanks in advance.

#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::string;
using std::endl;
int main()
{
string s;
while (cin >> s)
cout << s << endl;
return 0;
}


推荐答案


问题是>>遇到第一个空格
字符时,运算符停止读取,但是在这种情况下为什么会输出
完整输入字符串
,即使我们有白色字符串中的空格

The problem is >> operator stops reading when the first white space character is encountered but why is it in this case it outputs the complete input string even if we have white spaces in our string

因为您正在循环使用它。因此,每次 cin 左右时,您都会打印一个单词并丢弃空格。您在每个单词后打印换行符的事实意味着您不希望看到空格-实际上 s 不包含空格。

Because you're using it in a loop. So each time around cin eats a word which you print and discards whitespace. The fact that you're printing a newline after each word means you don't expect to see whitespace - and in fact s contains none.

一种简单的测试方法是打印:

A simple way to test this would be to print:

cout << s << "$";






但是,代码最有趣的特征是 while 测试由<< 返回的 istream 在布尔型上下文中,它恰好产生您想要的:输入是否完成。


However the most interesting characteristic of the code is how the while tests the istream returned by << which in a boolean context yields exactly what you want: whether the input is done or not.

这篇关于使用while(cin&gt; x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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