Pregunta

I have gone through many posts on SO , but still i am not able to resolve the issue .
I have to read :

text
pattern1
pattern2

from standard input , there are many text and patterns .
Code :

string t,p1,p2;
while(getline(cin, t))
{
    cin>>p1;
    cin>>p2;

    cout<<"text is = "<<t<<"\np1 is = "<<p1<<"\np2 is = "<<p2<<endl;
}  

Input file :

hammer
ham
mer
gogoa
go
z
gogoa
g
o

Output :

text is = hammer
p1 is = ham
p2 is = mer
text is =
p1 is = gogoa
p2 is = go
text is =
p1 is = z
p2 is = gogoa
text is =
p1 is = g
p2 is = o

¿Fue útil?

Solución 2

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

Otros consejos

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;
} 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top