我已经在SO上发了很多帖子,但我仍然无法解决问题 我必须阅读:
文本
模式1
pattern2
来自标准输入,有很多text and patterns
代码:
string t,p1,p2;
while(getline(cin, t))
{
cin>>p1;
cin>>p2;
cout<<"text is = "<<t<<"\np1 is = "<<p1<<"\np2 is = "<<p2<<endl;
}
输入文件:
锤
火腿
滨海
gogoa
去
ž
gogoa
摹
o
输出:
text is = hammer
p1 =火腿
p2 = mer 文字是=
p1 = gogoa
p2 = =去
文字是=
p1 = z p2 = gogoa
文字是=
p1 = g p2 = o
答案 0 :(得分:2)
#include <vector>
vector<string> vs;
int i;
while(getline(cin, t)) {
vs.push_back(t);
}
for(i = 0; i < (vs.size / 3); i++) {
cout <<"text is " << vs[0 + (3*i)] << "\np1 is " << vs[1 + (3*i)] << "\np2 is " << vs[2 + (3*i) << endl;
}
答案 1 :(得分:1)
如果您在cin >> something
之后使用getline,则需要在两者之间刷新缓冲区。
#include <iostream>
#include <limits>
using namespace std;
int main() {
string t,p1,p2;
while(getline(cin, t))
{
cin>>p1;
cin>>p2;
cout<<"text is = "<<t<<"\np1 is = "<<p1<<"\np2 is = "<<p2<<endl;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); // Dump everything until newline
}
return 0;
}
答案 2 :(得分:0)
试试这个:
string t,p1,p2;
while(getline(cin, t))
{
cin>>p1;
cin>>p2;
getchar(); //removes '\n' from stdin
cout<<"text is = "<<t<<"\np1 is = "<<p1<<"\np2 is = "<<p2<<endl;
}