代码之家  ›  专栏  ›  技术社区  ›  Samuel Burns

成功使用连续while(cin>>输入)[重复]

  •  0
  • Samuel Burns  · 技术社区  · 8 年前

    while(cin >> cel)

    int main() {
        double fah = 0;
        cout << "Enter a fahrenheit value:\n";
        while (cin >> fah) { // executes until a non-number input is entered
            cout << fah << "F == " << fah_to_cel(fah) << "C\n";
        }
        // tried cin.clear();  here
        // tried cin.clear(ios_base::eofbit); here
        double cel = 0;
        cout << "Enter a celcius value:\n";
        while(cin >> cel) { // executes until a non-number input is entered
            cout << cel << "C == " << cel_to_fah(cel) << "F\n";
        }
        return 0;
    }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Benjamin Lindley    8 年前

    你打电话是对的 cin.clear() 。重置的错误标志 cin ,在执行任何其他输入操作之前,您需要执行该操作。但你还需要做一件事。当输入失败时,任何字符 cin公司 正在尝试读取保留在输入缓冲区中的内容。因此,当您再次尝试收集输入时(在清除错误后),它将再次失败。因此,您需要删除留在缓冲区中的数据。你可以这样做:

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

    这说明

    在我看来,这是一种非常笨拙且容易出错的用户输入方式。我建议你只使用 std::getline ,它应该永远不会失败(除非在不太可能发生的内存分配失败的情况下)。然后手动解析生成的字符串,这使您能够更好地控制输入的形式。