我为一个学校项目编写了这个程序,用户输入最多4行文本,然后输入“end”,然后以相反的顺序重复它们。它工作正常,除了识别“线”只有1个字所以如果我尝试键入一条线(例如快速棕色狐狸跳过日志)它不会将其用作一条线而是每个字都是一条线。
#include <iostream>
using namespace std;
#include <string>
int main()
{
string l1;
string l2;
string l3;
string l4;
string l5;
bool end (false);
while (end == false)
{
cout<<"Welcome! Type one sentence then press enter, up to 4 sentences. When finished$
cin >> l1;
if (l1 == "end")
{
cout << "Error! Must enter at least 1 line of text!" << endl;
break;
}
cin >> l2;
if (l2 == "end")
{
cout<<l1<<endl;
end = true;
break;
}
cin >> l3;
if (l3 == "end")
{
cout<<l2<<endl;
cout<<l1<<endl;
end = true;
break;
}
cin >> l4;
if (l4 == "end")
{
cout<<l3<<endl;
cout<<l2<<endl;
cout<<l1<<endl;
end = true;
break;
}
cin >> l5;
if (l5 == "end")
{
cout<<l4<<endl;
cout<<l3<<endl;
cout<<l2<<endl;
cout<<l1<<endl;
end = true;
break;
}
else
{
cout<<"Error! Please enter 4 or less lines"<<endl;
break;
}
}
}
答案 0 :(得分:2)
使用std::getline
代替operator>>
。 operator>>
读取单词,而不是文本行。