while(cin>>word)

来源:互联网 发布:淘宝买活体动物可靠吗 编辑:程序博客网 时间:2024/06/16 05:33
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
        vector<int> A,B,C;
        int temp;
         
        cout<<"input A,finished by a character"<<endl;
        while(cin>>temp)
                A.push_back(temp);
         
         
        cout<<"input B,finished by a character"<<endl;
        while(cin>>temp)
                B.push_back(temp);
         
         
        cout<<"input C,finished by a character"<<endl;
        while(cin>>temp)
                C.push_back(temp);
 
         
        for(int i=0;i<B.size();i++)
                cout<<B[i]<<" ";
        cout<<endl;
        return 0;
}

 

这段代码意在输入若干整数,以输入一个字母结束输入。可是我发现这段代码好像只运行第一个while循环。
我怀疑是缓冲问题所以在每个 while循环后加上cin.ignore()。
结果还是没有解决问题。后来问张杰才知道在每一个while()之后加上

 

 

1
2
cin.clear();  //清除错误状态
cin.ignore();//跳过无效数据

 

才能最终解决问题。

后来仔细想了想,问题出在输入流cin。cin是一个输入流对象,当进行第一个while循环时我们输入一个字母来结束循环,而最后输入字母完全是为了结束输入数字,这个字母再没有任何意义,所以要加上cin.ignore()来路过无效数据,而此时第二个while(cin>>temp),因为用同一个cin对象,所以也被判断为false造成循环没有像我们预先想的那循环下去,因此要加上cin.clear();清除错误状态,才能再次使用while(cin>>temp)来执行输入操作。

这个以前还真没有注意过,发上来大家也注意注意。


while(cin>>word) cout<<word<<endl;的相关问题

如果输入123    123为什么输出的是123再另起一行123


首先要知道while(cin>>word)是怎么工作的while(cin>>word)就是,从输入流中,以空格为分隔保存到word里面。输入123  321,其实是循环了两次,因此执行了两次cout,第一个输出的是123,换行,第二个输出的是321,换行
追问:
但我有疑问就是循环的话那么是判断一次循环条件再执行一次循环体呀,既然word是string,为什么不能说123   123就是一个字符串
追答:
123   123可以是一个字符串,但cin的规则就是,将输入流里面,空格以前的赋值给word,如:#include <iostream>#include <string>using namespace std;void main(){string s;cin >> s;cout << s << endl;}你输入:324324 12344输出的是:324324而如果你设定s = "sdfdsf  sdfasdf";输出的就是:sdfdsf  sdfasdf问题不出现在字符串那里,而是在cin那里,它读到空格就不再读下去了,while的下一次使它读空格以后的东西

0 0
原创粉丝点击