Jul 7, 2011 at 9:55pm UTC
Hey can anyone help me with this simple program I wrote. I can't figure out why it keeps skipping a cin... Any help is much appreciated!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter a sentence: " ;
string sentence1;
getline(cin,sentence1);
cout << sentence1 << endl;
cin.clear();
cin.sync();
cout << "Enter another sentence: " ;
string sentence2;
getline(cin,sentence2);
cout << sentence2 << endl;
cin.clear();
cin.sync();
cout << "Again, enter a sentence: " ;
string sentence3;
getline(cin,sentence3);
cout << sentence3 << endl;
cin.clear();
cin.sync();
cout << "Again, enter a sentence: " ;
string sentence4;
getline(cin,sentence4);
cout << sentence4 << endl;
return 0;
}
Enter a sentence: Hello c++ forums
Hello c++ forums
Enter another sentence:
Again, enter a sentence: Why did it skip that line?
Why did it skip that line?
Again, enter a sentence:
Solution code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <iostream>
#include <string>
using namespace std;
int main()
{
cin.clear()
cin.ignore(256, '\n' );
cin.sinc();
cout << "Enter a sentence: " ;
string sentence1;
getline(cin,sentence1);
cout << sentence1 << endl;
cin.ignore(256, '\n' );
cout << "Enter another sentence: " ;
string sentence2;
getline(cin,sentence2);
cout << sentence2 << endl;
cin.ignore(256, '\n' );
cout << "Again, enter a sentence: " ;
string sentence3;
getline(cin,sentence3);
cout << sentence3 << endl;
cin.ignore(256, '\n' );
cout << "Again, enter a sentence: " ;
string sentence4;
getline(cin,sentence4);
cout << sentence4 << endl;
return 0;
}
Last edited on Jul 9, 2011 at 4:58am UTC
Jul 8, 2011 at 12:32am UTC
g++, use spaces in your sentence instead of just "test"...
Last edited on Jul 8, 2011 at 12:33am UTC
Jul 8, 2011 at 1:11am UTC
so it's my compiler that's the problem? What compiler are you using?
Jul 8, 2011 at 4:19am UTC
it works fine for me as well... i use microsoft visual studio 6.
Jul 8, 2011 at 7:19am UTC
the code worked for me as well ..on visual studio 2008 express edition ..
Jul 8, 2011 at 10:17pm UTC
It is. Try replacing cin.sync() with std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');