I need to create a program that takes a users info for a check and displays it in a check form. Heres an example:
date: 2/23/2010
name: William Schmidt
amount, dollars: 23
cents: 30
payee: Office Max
your check:
William Schmidt 2/23/2010
pay to: Office Max $23.30
twenty three and 30/100 dollars
This is what I have at the beginning of the program but the program closes once the user inputs their name. Why is this? Do i need two separate strings? One for the first name and one for the last? This is my first day of strings so I am new to it.
The reason it would be exiting as soon as you put in your name is because the cin>> command, when entering strings, only gets up to the first space / endline character. Once that is done, it assumes that is the only thing you will be doing with that variable, and goes to input the next input into the next variable. Because there is a space in the name, it reads "William" into name, then tries to input "Schmidt" into the integer field, which fails.
To correctly get the input, use getline(). An example of this is:
cout << "Please input the following check information:\n"
<< "date: ";
getline(cin, date);
This would allow the full line to be read into "date". Likewise, "getline(cin, name);
There are some compatability issues with using cin and getline() in the same program one after the other, check out their respective pages on this site to get the relative info.
Using cin >> date is leaving a newline '\n' in the input buffer.
getline() has a default delimiter of '\n'. Which in your case, make's it skip that line.
Now, as date is a string, you should also use getline() for input there too!
Also,
ATDR2012 wrote:
There are some compatability issues with using cin and getline() in the same program one after the other, check out their respective pages on this site to get the relative info.
Okay the next problem I came across is that when I try to output the string payee it only outputs the first name because i didn't use getline again. But if I use getline it doesn't work because I have a cin for the integer variables before the string payee. What do i do?
I understand that you are supposed to use getline(); when it is a string but it skips the line because i have a cin >> for the integer variable the line before that.
Okay thank you I read that link earlier but I didn't fully undertand. So basically line 12 lets getline(); work after a cin >> operator right? Also quick question, why don't you just globally define "using namespace std;" instead of having std:: everywhere? Are there perks to using it your way?
It clears the input buffer, i.e. std::cin. Which is removing the '\n' that's left. When it is there, your program lands on the getline() function and see's it has a '\n' in the buffer, which is the delimiter( get up to this character ) and takes it as input.