c++如何忽略错误的数据输入?

标签 c++

(标题很糟糕,请帮忙修改)我正在编写一个函数,要求用户输入一个整数,如果输入数据不是整数类型,该函数将返回警告。但似乎只要用户输入是“char”/“string”,该函数就会一次接收一个字符,因此会打印多行警告消息。有没有一种方法可以让函数将错误输入作为一个字符串?或者只是忽略整个输入?

代码如下:

cout << "Please entre the number of data points (please enter an integer): \n";
cin >> dataNum;
while (cin.fail())
{
    cout << "Please enter an integer number. \n";
    cin.clear();
    cin.ignore();
    cin >> dataNum;
}

当我尝试在 .dat 文件中获取检查数据时,出现了类似的问题。我正在从 .dat 文件中提取“双”类型,但有一行包含字符串。有什么办法可以将这条线解释为一个整体吗?或者干脆跳过这条线?代码如下:

ifstream myfile(fileName);
if (!myfile.good())
{
    cerr << "Error: the file '" + fileName + "' cannot be opened. \n";
    return(1);
}

// Dynamically allocate memory for data
double *mydata = new double[dataNum + 1];

// Read data from file, ignoring any additional bad data
while (!myfile.eof())
{
    if (myfile.fail())
    {
        cerr << "Error: Rogue data detected. Bad data will be ignored. \n";
        myfile.clear();
        myfile.ignore();
        n--;
    }
    myfile >> mydata[n];
    n++;
}

// Close file
myfile.close();

最佳答案

问题

您需要保证double的有效输入类型。您遇到的具体问题是,当您遇到错误状态时,您没有忽略足够的无效输入流。您需要重置错误状态,然后忽略当前流中的所有内容,然后再重试。

示例解决方案

double dataNum;
// we need to enforce that the input can be stored in double type
while(!(std::cin >> dataNum))
{
    std::cout << "Invalid value! Please enter a number." << std::endl;
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

它的作用

std::cin流有一个错误位std::cin.fail()在无效输入上设置的值(在我们的例子中,任何不会转换为 double 类型的内容。 std::cin 中的错误位是粘性的,因此当我们遇到无效输入时,我们必须 std::cin.clear() 错误状态,然后 std::cin.ignore() 输入流中当前可能存在的任何数据。您需要忽略流可能能够容纳换行符的最大字符数,因为在输入流中可能存在各种无效的内容然后,我们循环直到输入流收到可以存储到 double 类型中的有效数据。std::numeric_limits 位于 #include <limits> 中。

关于c++如何忽略错误的数据输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48688592/

相关文章:

c++ - Xcode 8.3 命令行 C++

c++ - C++ 中的原子性 : Myth or Reality

python - 从 boost::python::object 列表中获取单个元素,用于 python 例程

c++ - wxWidgets:获取一些唯一的机器 ID 以用于验证/注册

c++ - C++ 代数库

c++ - 从 vector 中删除最小的非唯一值

c++ - 在C++中获取调用者的地址

C++ 现代字符串指针

c++ - 模板的隐式特化是什么意思?

c++ - 在类似于列表和 unordered_maps 的 boost 或 STL 线程安全容器中吗?