read strings from input till EOF

放肆的年华 提交于 2019-12-06 05:57:20
Marco A.

If you're using getline after cin >> something, you need to flush the newline out of the buffer in between.

#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

More here: https://stackoverflow.com/a/10553849/1938163

you could try something like this:

#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;
}

Try this:

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;
} 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!