My program won't work!!!!

Started by
5 comments, last by Aardvajk 15 years, 5 months ago
Whenever I build my program it has no errors, but when I try to run it, it doesn't show the get line part. I'm new, so if anyone can give help, I'd be really greatful. Here's the code: IF YOU WANT TO SEE WHAT I MEAN COPY THE PROGRAM WITHOUT THIS AND BUILD/RUN IT. IF YOU SOLVE IT PLEASE REPLY. (CAPITALS DURING THE PROGRAM ARE THINGS I PUT IN TO HELP YOU, DON'T COPY THEM) #include <iostream> #include <string> #include <istream> #include <ostream> using namespace std; using std::getline; int main() { //welcoming the user std::cout << "Welcome to the Crazy News Network!" << endl; // start of questions (might not work,if bugged check here second) std::string userName; std::cout << " Please type in your first name." << endl; std::cin >> userName; int smallNumber; cout << "How many sibiling do you have?" << endl; cin >> smallNumber; float largeNumber; cout << "How much money would you like to earn per year?" << endl; cin >> largeNumber; std::string color; std::cout << "What is your least favorite color?" << endl; std::cin >> color; //start of "getline" functions, will really get messed up, check first std::string veggie; std::cout << "Which vegetable do you think has the weirdest shape?" << endl; getline (cin,veggie); THIS IS THE PART THAT DOESNT WORK cout << veggie << endl; return 0; }
Advertisement
learn to debug.
mpipe, that was uncalled for.

Add this line after cin>>color;

cin.ignore();


The reason this is needed is because cin>>color is grabbing the integer and ignoring the newline entered when you press return. So getline sees that and thinks you're done entering the line. cin.ignore gets rid of that newline character.
Also note that if you write "using namespace std;" this is usually not to have to write std:: in front of these functions.
Adding to what thedirt said, a std::cin.ignore(1); before your getline should solve your problem.
thanks every1, my program's working now. I think thedirt's part really fixed it.

[Edited by - ulxlx71 on November 15, 2008 5:41:33 AM]
ulxlx71 - when dealing with keyboard input, this is why it is normally a pretty good idea to read a whole line of input at a time and the process the input in a stringstream:

A rough example:

template<class T> bool get_input(T &t){    std::string s;    std::getline(std::cin,s);    std::istringstream is(s);    T t;    is >> t;    return !is.fail();}void f(){    std::cout << "What is your first name?\n";    std::string first;    get_input(first);    std::cout << "How old are you?\n";    int age;    while(!get_input(age)) std::cout << "Please enter a valid number\n";}


This way, not only is an entire line of input consumed each time, but it makes it easier to catch conversion errors, like with the "age" example above.

And you never need to std::cin.ignore() again.

This topic is closed to new replies.

Advertisement