Hi,
I've noticed the following behavior using cin.get() and am not sure why... I'm hoping someone may be able to enlighten me.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <string>
using namespace std;
char cLastInput[50];
int main()
{
string sFirstName;
string sLastName;
cout << "First Name: ";
cin.get(cLastInput, 50);
sFirstName = string(cLastInput);
cout << "\nLast Name: ";
cin.get(cLastInput, 50);
sLastName = string(cLastInput);
cout << "\n\n" << sFirstName << " " << sLastName;
return 0;
}
|
First Name: Jack
Last Name: Jack
Process returned 0 (0x0) execution time : 2.200 s
Press any key to continue. |
The program takes the first name input, but does not prompt me for the last name input, and seems to retain the value of cLastInput for the second cin.get() call.
My intent was to use a single variable to hold temp input that could be converted to a string and applied to variables, though it appears that subsequent cin.get() calls using the same variable as the last call without prompting in the console for a replacement.
Could somebody possibly explain why cin.get() does this?
For further background, I've come to use cin.get() as it seems to be the most convenient way to return a string from the console that does not break on a space. So far, through minor excersizes to familiarize myself with some basic ins and outs of c++, this is the best I've gotten to yet. Should I instead be looking at stringstreams, instead of strings and char arrays? I will look into them, as I haven't yet, but I'd still be curious to know the reason for this cin.get() behavior.
Many thanks in advance,
Jack