我不了解getline +字符串是什么?

时间:2011-11-23 19:51:01

标签: c++ arrays string getline

这是我第一次使用stackoverflow。我一直无法找到关于getline的所需信息。我是一个简单的工程转移编程类,所以我们编写的代码非常简单。我在这里尝试做的就是将用户定义的问题和答案放入两个不同的数组中。我的while循环看起来像这样(我正在使用for循环,但切换到只是为了看它是否会停止破坏):

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;
        */
    }
}

我注意到输入部分的答案以及保存数据仅用于调试。当我运行程序时,它跳过第一个问题的getline,显示第二个循环“输入问题”,getline适用于其余部分。因此,如果我的size1为5,则程序仅填充阵列位置1-4。请帮忙。 这是一个简单的闪存卡程序,它可以像创建闪存卡一样进行研究和随机播放。

1 个答案:

答案 0 :(得分:13)

它出现跳过第一次迭代的原因是因为当你做

cin >> size1;

输入一个数字并按Enter键。 cin读取整数并将换行符留在缓冲区上,这样当你调用getline时,就像你立即点击回车键一样,{{1}什么都不读(因为它在读取换行符之前停止),丢弃换行符,并将空字符串放在getline中。这就是quest1[0]的其余部分“正确”工作的原因。

在你的循环上方添加getline以摆脱延迟的cin.ignore('\n'),这应该会使其正常工作,除非代码中出现其他错误。

不要忘记将'\n'改为x = x++以避免UB。

相关问题