PDA

View Full Version : C++, Odd "cin" behavior.



cgroza
October 1st, 2010, 07:32 PM
Hello, I built my address book in C++ and it seems to work, but for example if I create a new entry and give input with a space in it , the characters after the space are assigned to the next cin command. Here is the code:



string name,telnr,address,email;
cout << "Enter the name:" << endl;
cin >> name;
cout << "Enter the phone number:" << endl;
cin >> telnr;
cout << "Enter the address:" << endl;
cin >> address;
cout << "Enter the email:" << endl;
cin >> email;

ofstream dafi;
dafi.open(homedir.c_str(),ios::app);

dafi << name <<" | ";
dafi << telnr<<" | ";
dafi <<address<<" | ";
dafi << email <<endl;

dafi.close();


So when it asks my name if I put in there "Chuck Norris", Chuck will be in the name variable and Norris will be in the telnr variable.

TheBuzzSaw
October 1st, 2010, 07:37 PM
http://www.cplusplus.com/reference/string/getline/

schauerlich
October 1st, 2010, 07:39 PM
When cin reads in a string, it reads to the next whitespace. To get a whole line, use getline (http://www.cplusplus.com/reference/string/getline/).

cgroza
October 1st, 2010, 07:39 PM
So I should use getline(cin,str); instead?

schauerlich
October 1st, 2010, 07:41 PM
So I should use getline(cin,str); instead?

yes.

cgroza
October 1st, 2010, 07:45 PM
yes.

I did, and now it asks me for my name but its skips instantly at the next ones.

TheBuzzSaw
October 1st, 2010, 07:53 PM
I did, and now it asks me for my name but its skips instantly at the next ones.

Did you use getline on every single one? You should.

cgroza
October 1st, 2010, 07:56 PM
Yes i did. The code looks like the other one except all lines with cin>>variable are replaced with getline(cin,variable).

TheBuzzSaw
October 1st, 2010, 08:26 PM
You'll have to post more of your code. I just ran a test, and it worked just fine.

cgroza
October 1st, 2010, 08:40 PM
It sounds weird but i added 2 of getline there and it works. Very weird.

dwhitney67
October 1st, 2010, 09:31 PM
It sounds weird but i added 2 of getline there and it works. Very weird.

Was this topic not discussed last week?

If you have three strings to read, use a getline() to acquire each.



using namespace std;

string str1, str2, str3;

cout << "Enter string 1: ";
getline(cin, str1);

cout << "Enter string 2: ";
getline(cin, str2);

cout << "Enter string 3: ";
getline(cin, str3);

...

cgroza
October 1st, 2010, 11:44 PM
Was this topic not discussed last week?

If you have three strings to read, use a getline() to acquire each.



using namespace std;

string str1, str2, str3;

cout << "Enter string 1: ";
getline(cin, str1);

cout << "Enter string 2: ";
getline(cin, str2);

cout << "Enter string 3: ";
getline(cin, str3);

...


Thats exactly what i did and i still got the problem, its fixed now, thanks.