C++ 循环while(cin>>s)结束的问题
#include<iostream>#include<string>usingnamespacestd;intmain(){strings1,s2;cout<<"Ente...
#include<iostream>#include<string>using namespace std;int main(){ string s1,s2; cout<<"Enter s1(Ctrl+Z to end):"<<endl; while(cin>>s1) cout<<s1<<endl; return 0;}程序的目的就是读入一个字符串,然后输出,直到输入Ctrl+Z结束。这个没有问题,但是如果改成下面的代码,就会不执行第二个循环:#include<iostream>#include<string>using namespace std;int main(){ string s1,s2; cout<<"Enter s1(Ctrl+Z to end):"<<endl; while(cin>>s1) cout<<s1<<endl; cout<<"Enter s2(Ctrl+Z to end):"<<endl; while(cin>>s2) cout<<s2<<endl; return 0;}望高手不吝赐教,谢谢。
展开
1个回答
2013-07-30
展开全部
改用getline()函数:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1,s2;
cout<<"Enter s1:"<<endl;
getline(cin,s1);
cout<<s1<<endl;
getchar();
cout<<"Enter s2:"<<endl;
getline(cin,s2);
cout<<s2<<endl;
return 0;
}
//结果:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1,s2;
cout<<"Enter s1:"<<endl;
getline(cin,s1);
cout<<s1<<endl;
getchar();
cout<<"Enter s2:"<<endl;
getline(cin,s2);
cout<<s2<<endl;
return 0;
}
//结果:
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询