-
vectors and user input
Hey everyone,
Today's question is sponsored by the topic of vectors and the letter h for "help"...
So, I'm using a vector of strings to accept user input. My code takes the users input and inserts it into the vector using the string variable with the user input as the argument passed into push_back():
Code:
string gameChoice;
//...some if else statements and a while statement follow...
cout << "\nEnter the name of your favorite game: ";
cin >> gameChoice;
gameList.push_back(gameChoice);
Well what happens is any single word input is used properly and everyone's happy but once it goes to multiple words it prints the 1st word and sends a blank field to the next iteration of the loop the whole thing is in (indicating the problem is with my cin statement...hwoever cin.get only accepts chars it seems...so any help would be awesome...)-Chap
By the way...did anyone else have any problems getting onto this website? I've been trying for the past 2 days but I was just getting an eternally loading homepage...just curious if anyone else was having trouble...
-
You can't use cin for strings containing multiple words. cin will stop at the first blank, that is what you are running into. You need to use getline with strings. Here is an example below that will probably help you out:
Code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(void) {
vector<string> myString;
vector<string>::iterator itString;
string input;
for(int x = 0; x<5; x++) {
cout<<"Enter your favorite game: ";
getline(cin, input);
myString.push_back(input);
}
for(itString = myString.begin(); itString != myString.end(); itString++) {
cout << *itString;
cout<<endl;
}
return 0;
}
Happy Coding!!
-
so what exactly is the cin argument in getline?
-
The first argument to string::getline is an istream object, in this case we are using cin for the object. Any istream object would suffice. Obviously the second argument is the string.
-
I know this isn't a very big deal, but...aww screw it I'll do it anyways! This is America!
Code:
For C++
The following are acceptable uses:
int main ( int argc, char *argv[] )
int main ()
The first option follows similar conventions to those used by C99.
The second option is used when you do not require access to the command
line arguments, and is equivalent to the int main(void) option used by C99
From CProgramming.com FAQ
The code you posted used int main(void), that's a C way of saying no arguements. In C++, we should use int main(). I hate myself now :(
-
yes, and I do know the standard. I've read it a few times. Yet, I do not like it so I'll stick with C99 approach. I am sure I will get stoned for it by somebody around here but I like to live dangerously. :p
-
We live in a dangerous world! lol