Question:
C++ Programming. Please Help!!!!?
Stephanie
2012-05-03 20:55:02 UTC
http://pastebin.com/DDLXuLNg
My program skips getting input from user for first name. I think it because it assumes getnextline. I can't use cin>>firstline.....because it gets messed up if I put space for two words or more.
Is it possible to make a function for it? If so, how? PLEASE HELP!!!!
Three answers:
oops
2012-05-03 21:43:54 UTC
The problem is your mixed usage of operator>> and getline. operator>> stops when it finds whitespace, and leaves it in the input buffer. This includes newlines, which are put into the buffer whenever you press the enter key. Now, because a newline is exactly the thing that getline is looking for, you have a problem when you use operator>> then follow it up with getline. operator>> leaves the newline in there, and getline sees it and then its job is done, so it doesn't prompt for user input.



There are a few ways you can go about fixing this problem. One is to avoid operator>> entirely, only use getline. Now of course, getline doesn't read numbers, only strings, so you will need to use string to number conversion routines when you want numbers. For your case, you are only using operator>> to read a char, so you can easily change that char to a string, and use getline with it, and compare it as a string (i.e. if (choice == 'a' || choice == 'A'))



I would prefer the previous method, but if you want to continue to use a char with operator>>, then you can clear the buffer out after you use it, like this:



    cin >> choice;

    cin.ignore (10000, '\n');



That will read up to 10000 characters or until it finds a newline, then it will discard it all. You could also use the more technically correct:



    cin.ignore( numeric_limits::max(), '\n');



But I find that to be a terrible eye sore, and 10000 should be sufficient.
Brian
2012-05-04 04:53:53 UTC
If the first getline() call is returning immediately and seems to return an empty string, then that pretty much indicates that there's a "\n" (new line) character at the front of the buffer. You can try clearing the cin buffer before calling getline.



#include



// This effectively resets the cin buffer.

cin.ignore(std::numeric_limits::max()); // read to EOF

cin.clear(); // reset error state flags



// Now you can call getline() on cin and be confident that the buffer is empty.

string str;

getline(cin, str);
anonymous
2012-05-04 04:01:28 UTC
You can use gets() function.

Example:

char *name;

gets(name);


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...