1

I am trying to get the user to input some data and then storing it in a structure, however I am having troubles knowing which function I should use and what's the difference? cin or getline()? Either function I use, it seems like it takes in the '\n' key and makes my program crash, but I am not 100% if that's the problem... Since it keeps crashing.

I've played around with both of them and here is what I have.

string temp;
int id;

cout << endl << "Full name (last, first): ";
cin >> temp;
cin.ignore(1, '\n');
myData[fileSize] = parseName(temp);

cout << endl << "ID: ";
cin >> id;
myData[fileSize].id = id;

cout << endl << "Address: ";
cin >> temp;
temp.copy(myData[fileSize].address, temp.length(), 0);

The variable fileSize is just which element the array is currently at and the function parseName splits the name into last and first.

I been reading on a couple of functions like, cin.ignore() and noskipws, but not sure how to use them. By the way, the way the user should input the data is "last, first", with a comma and white space after (this is what the parsing function is looking for).

Also I am not sure if the address section is the best way to do this, I have the structure myData.address to be a character array, because I don't know how to work with strings. I am still not confident with C++. Thanks for any help.

EDIT: If I comment out the ID and Address parts, the program loops itself 6 times saying I have an invalid entry (which is part of main), so it reads 6 or 7 keys after I press enter. If I leave everything the way it is, this is what I get.

    Full name (last, first): terminate called after throwing an instance of 'std::ou
t_of_range'
  what():  basic_string::copy

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Process returned 3 (0x3)   execution time : 4.328 s
Press any key to continue.
Maty
  • 95
  • 2
  • 12

1 Answers1

0

You should use cin.getline() instead for this case, and the cin.ignore is not necessary.

Here is an examination of the two methods - std::cin.getline( ) vs. std::cin

Also, check your parseName function and try testing it in isolation without any user I/O.

Community
  • 1
  • 1
djdanlib
  • 21,449
  • 1
  • 20
  • 29
  • I checked the parse by hardcoding in a name, and it works. How do I get rid of the '\n' key though? Cause all before this I have a cout saying if you would like to add a contact, and the user has to press the 'Y' key, and I'm guessing that new line just before this function is what is causing it to freak out. I say this because after modifying the code a bit, when I press 'Y' to add a contact, it skips right over the adding name part and goes back to the original loop (all of this while address and id are being commented out). – Maty Jan 13 '15 at 14:52