Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What am I not understanding about getline+strings?

This is my first time using stackoverflow. I've been unable to find out the information I need regarding getline. I'm in a simple programming class for engineering transfers so the code that we write is pretty simple. All i'm trying to do here is put a user-defined number of questions and answers into two different arrays. My while loop looks like this (I was using a for loop but switched to while just to see if it would stop breaking):

int main ()
{
    srand((unsigned)time(0));
    string quest1[100], answ1[100];
    int size1, x = 0, num, count1, visit[100], shuffle[100];
    fstream flashcard1; 

    cout << "flashcard.cpp by NAME\n" << endl;
    cout << "This program allows user to manipulate questions and answers for studying.\n" << endl;
    cout << "\nHow many flash cards will be entered(MAX 100)? ";
    cin >> size1;
    cout << endl;

    while(x < size1)
    {
        cout << "Enter Question: ";
        getline(cin , quest1[x]);
        cout << endl;
        x = x++;

        /*
        cout << "Enter Answer: " << endl;
        getline(cin,answ1[x]);
        cout << endl;
        flashcard1.open("flashcard1.dat", ios::app);
        flashcard1 << quest1[x] << " " << answ1[x] << endl;
        flashcard1.close();
        cout << "Data Stored." << endl;
        */
    }
}

I noted out the answer entering part as well as the saving data to the file just for debugging. When I run the program it skips the getline for the first question, displays the second loop of "Enter question" and the getline works for the rest of them. So if I have a size1 of 5, the program only fills array positions 1-4. Please help. This is a simple flash card program that will do the same thing as if you were to create flash cards to study and shuffle them.

like image 989
Brent Avatar asked Nov 23 '11 19:11

Brent


1 Answers

The reason it's appearing to skip the first iteration is because when you do

cin >> size1;

You enter a number and hit the Enter key. cin reads the integer and leaves the newline character unread on the buffer, so that when you call getline, it's as if you immediately hit the enter key, and getline reads nothing (because it stops before reading the newline character), discards the newline, and puts the empty string in quest1[0]. And that's why the rest of the getlines work "correctly".

Add cin.ignore('\n') above your loop to get rid of the lingering '\n', and that should make it work, barring other errors in your code.

And don't forget to change x = x++ to just x++ to avoid UB.

like image 186
Seth Carnegie Avatar answered Sep 26 '22 21:09

Seth Carnegie