【问题标题】:better method rather than using cin.ignore in c++更好的方法,而不是在 C++ 中使用 cin.ignore
【发布时间】:2020-04-20 04:53:12
【问题描述】:
int test, flag = 0;
cin >> test;
while (test--)
{
    if (flag == 0)
        cin.ignore(256, '\n'); // using because of whitespace reading due to cin
    string check;
    getline(cin, check);
    checkPangram(check, check.size());
    flag++;
}

如果我删除第 4 行,那么这个程序不会读取几个测试用例字符串,所以我使用标志值在启动时只执行第 4 行一次。 如果你能帮我找到任何通用方法,读取字符串(带空格),这样我即使在 cin 或 getline 之后也可以读取而不会丢失任何输入

【问题讨论】:

标签: c++


【解决方案1】:

您可以在进入循环之前简单地调用cin.ignore()

int test;
if (cin >> test)
{
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    while (test--)
    {
        string check;
        getline(cin, check);
        checkPangram(check, check.size());
    }
}

或者,您可以将std::getline() 用于所有输入,使用std::istringstream 从第一行读取test

int test;
string check;

getline(cin, check);
istringstream iss(check); 

if (iss >> test)
{
    if (test--)
    {
        getline(iss, check);
        checkPangram(check, check.size());

        while (test--)
        {
            getline(cin, check);
            checkPangram(check, check.size());
        }
    }
}

【讨论】:

    【解决方案2】:

    把它移出循环

    int test;
    cin >> test;
    cin.ignore(256, '\n');
    while (test--)
    {
        string check;
        getline(cin, check);
        checkPangram(check, check.size());
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 2011-03-02
      • 2022-08-16
      相关资源
      最近更新 更多