从输入读取字符串直到EOF

时间:2014-03-30 09:50:04

标签: c++ io eof getline

我已经在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

3 个答案:

答案 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;
}

http://ideone.com/b7Xj6o

更多信息:https://stackoverflow.com/a/10553849/1938163

答案 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;
}