您好,我正在解决 Stanley 所著的 C++ Primer 一书中的一个问题。问题是:-
编写一个程序,一次读取标准输入一行。修改您的程序以一次读取一个单词。
我使用了选择变量,用户可以通过它切换到所需的输出,即是打印一行还是一个单词。 Line 输出是正确的。但是,单词输出并不正确。因为,我想在空格之前打印单词。但即使在空格之后它也会打印整个句子。
以下代码:-
#include<iostream>
using namespace std;
int main(){
char select;
string line,word;
cout<<"please enter w(word) or l(line)";
cin>>select;
if(select=='l'){
/* program to read one line at a time */
while(getline(cin,line)){
cout<<line;
}
}
else if(select=='w'){
/*program to read one word at a time */
while(cin>>word){
cout<<word;
}
}
else {
cerr<<"you have entered wrong input!"<<endl;
return -1;
}
return 0;
}
我希望它只打印 shubharthak,因为我只使用 cout<
#include<iostream>
using namespace std;
int main(){
string s;
cin >> s;
cout << s;
return 0;
}
答案 0 :(得分:0)
这是因为 while
循环。删除它,程序按预期工作。
#include<iostream>
using namespace std;
int main()
{
char select;
string line,word;
cout<<"please enter w(word) or l(line)";
cin>>select;
if(select=='l')
{
while(getline(cin,line)) { cout<<line; }
}
else if(select=='w') { cin >> word; cout<<word; }
else
{
cerr<<"you have entered wrong input!"<<endl;
return -1;
}
return 0;
}
结果:
please enter w(word) or l(line)w
test1 test2 test3
test1