I wrote a program to test if I could successfully input text from my keyboard into different vectors and then have the program output all the text.
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
|
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s;
vector<string> first;
vector<string> second;
cout << "enter strings of words for the first column." << endl;
while (getline(cin, s))
first.push_back(s);
cout << endl;
s.clear();
cin.clear();
cout << "enter strings of words for the second column." << endl;
while (getline(cin, s))
second.push_back(s);
cout << endl;
for (vector<string>::const_iterator i = first.begin(); i!=first.end(); ++i)
cout << *i << endl;
for (vector<string>::const_iterator i = second.begin(); i!=second.end(); ++i)
cout << *i << endl;
return 0;
}
|
In my code, the user is supposed to input lines of words for one vector, and then another set of lines for a second vector. The program is then supposed to output each line on the screen.
My problem is that I never get to input text for the second vector. It seems my program skips over the second while loop on line 22. Actually, I'm pretty sure it skips over the second while loop. I don't know why the getline function is returning a false bool, other than the possibility that cin is still in a fail state. I don't know why it would be, because I thought calling cin.clear() took care of that.
I am on Mac OSX Snow Leopard, typing out my code on TextWrangler, and compiling, building, and running everything in the Terminal window with g++.
I gave my code to a friend who is running Visual C++ on Windows 7. He says the code works perfectly on his computer and he gets to input lines of text for each prompt.
When I run my program, I get my first prompt. I then input something like:
asdsads <return> dfdfdsfsfs <return> sdfdfs <return> CNTRL-D
The program then prints out my second prompt, but doesn't stop to allow me to input anything. It then ends up printing out only the first vector, since the second vector never had an opportunity to be filled. The program then terminates.
I feel like it is a problem with how my Terminal window handles the end of file command. I understand that when I type in CNTRL-D the first time, it puts cin in a fail state, but for some reason the implementation doesn't seem to listen when I ask it to cin.clear().
Any help would be appreciated. I just started learning C++ two weeks ago and I'm very new at this. Thank you in advance.