为什么这会导致chars无限循环而不是双倍?

时间:2016-07-08 15:41:09

标签: c++ loops

我觉得我正在做一些非常愚蠢的错事。我只是希望程序告诉用户何时输入非双打,并继续循环回到输入值的cin。

我希望用户输入任何数字。然后必须做这个琐碎的数学并重复。它在这方面工作正常,当输入一些像char这样的意外输入时出现问题。然后输入以某种方式将它发送到一个循环中,它循环数学问题,而不是告诉用户他们必须键入一个数字并循环回一个新数字的cin类型。

#include <iostream>
#include <cstdlib>

using std::cout; using std::cin; using std::endl;

long double domath(long double i)
{ 
     cout << i << "/" << 2 << "=" << i/2 << endl;    
     cout << i/2 << "*" << 10 << "=" << (i/2)*10 << endl << endl;   
     cout << 5 << "*" << i << "=" << 5*i << "\n\n";      
     return 0;
}

int main()
{

    long double in = 0;

    while(true)
    {
        cin >> in;         
        if (cin.fail()) {             
            in = char(int(in));  
        }           
        domath(in);
    }
    system("pause>nul");
    return 0;
}

2 个答案:

答案 0 :(得分:1)

如果失败,你不会清除cin,它会无限地尝试解析错误的输入以使其加倍,每次都失败。如果出现错误,您需要清除缓冲区:

if (cin.fail()) {
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    in = char(int(in));
}

另外,无法理解你想用

实现的目标
in = char(int(in));

in是一个很长的双变量,它将保留你赋给它的最后一个值,不需要“转换”它来做数学。

答案 1 :(得分:0)

你不能尝试做这样的事吗?

int x;

if(std::cin >> x)
  doSomethingCool(x);
else
  std::cout << "Error, not a valid integer!" << std::endl;

在输入错误时退出循环。

我认为这比清除缓冲区和所有其他爵士乐更自然/看起来更干净。只是我的意见。

if (cin >> x) - Why can you use that condition?

编辑:Bul的答案仍然很好。