循环读取数据时,Char获得垃圾值

时间:2020-05-23 17:18:47

标签: c++ stdin getline

我在循环读取数据时遇到问题。尽管在我看来代码不错,但是对于某些测试用例来说,它还是很糟糕的。这是简化的程序代码。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int n;
    string str1, str2, str3;
    char choice;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> choice;
        cin.ignore();
        getline(cin, str1);
        if (choice == 'a') {
            getline(cin, str2);
            getline(cin, str3);
            // ...
            // operations not related to data input
            // ...
        } else if (choice == 'b') {
            getline(cin, str2);
            // ...
            // operations not related to data input
            // ...
        } else if (choice == 'c') {
            // ...
            // operations not related to data input
            // ...
        }
    }
    return 0;
}

选择的输入值始终为'a','b'或'c',但在程序执行过程中有时会得到其他值。 我尝试使用scanf代替,但是它没有改变结果。 有谁知道如何解决这个问题?

0 个答案:

没有答案