-1

I have a problem with the getline function in the code below. In the "get" info section I want to be able to store a whole sentence, but I can't make it work.

When I open up my program it just skips the input for the info.

p.s: I'm new to C++

Here is the section of the code where i have the problem (Enter the information):

void add() {
    string name;
    string faction;
    string classe;
    string race;
    string info;

    ofstream wowdatabase("wowdatabase.txt", ios::app);
    cout << "Add a race or class" << endl;
    cout << "---------------------------------------------------------" << endl;
    cout << "" << endl;
    cout << "Enter the name of the race or class (only small letters!):" << endl;
    cin >> name;

    cout << "Enter Race (Type -, if writen in name section):" << endl;
    cin >> race;

    cout << "Enter Class (Type -, if writen in name section):" << endl;
    cin >> classe;

    cout << "Enter faction (Alliance/Horde):" << endl;
    cin >> faction;

    cout << "Enter the information:" << endl;
    getline(cin, info);

    wowdatabase << name << ' ' << faction << ' ' << classe << ' ' << race << ' ' << info << endl;
    wowdatabase.close();
    system("CLS");
    main();
}

Now it works fine =) but, when i want to output the info again it only shows the first word in the sentence?

2 Answers2

2

Before this statement

getline(cin, info);

make the following call

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

To use this call you must include header <limits>.

The problem is that after executing statement

cin >> faction;

the new line character that corresponds to enetered key ENTER is in the input buffer and the next getline call reads this character.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

After you read fraction an empty line character will be left over. The consequent call to getline will read it. To avoid that add a call to cin.ignore before the getline call.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176