c++ - 从文件中读取整数时的错误处理

标签 c++

很抱歉这个有点初学者的问题,但我已经处理了几天,但无法找到解决方案。

我基本上是从一个文件中读取整数,这些文件应该有一定数量的数字,为了这个问题的目的让我们说 40。当文件少于或多于 40 时我可以返回一个错误罚款整数。但是,如果那里碰巧有一个非数字字符,我就很难弄清楚如何返回错误。 这是我目前正在做的:

int number = 0;
int counter = 0;

while(inputstream >> number)
{
   // random stuff
   counter++;
}

if (counter < 40)
  return error;

在这一点上,我有点困惑该去哪里。当输入流不是 int 时,我的 while 循环将终止,但有两种情况可能会发生这种情况,其中存在非整数字符,或者已到达文件末尾。如果我们在 eof,我的错误消息很好,并且整数少于 40 个。但是,如果它在某处遇到非整数,我们也可能小于 40。我希望能够确定两者之间的区别,但很难弄清楚如何做到这一点。任何帮助,将不胜感激。谢谢!

最佳答案

您可以在循环中输入一行并尝试将其转换为整数,因此如果转换失败意味着非整数并立即中断循环并返回一个错误,告知找到了一个非整数。

否则继续读取直到文件末尾然后检查值是否小于或大于 40 检查循环是否读取所有内容或由于非整数值而中断:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

enum ERRORFLAG{INIT, LESS_40, MORE_40, NON_INT}; // enumerate error

int main()
{

    ifstream in("data.txt");

    string sLine; // input one line for each read
    int value; // value that will be assigned the return value of conversion
    int count = 0; // counter for integer values
    ERRORFLAG erFlag = INIT; // intialize the error flag

    while(getline(in, sLine)) // iterate reading one line each time
    {
        if( !(value = atoi(sLine.c_str()) ) ) // conversion from string to integer so if the conversion failed else body will be executed
        {
            erFlag = NON_INT; // setting the error flag to non-int and break
            break;
        }
        else
            count++; // otherwise continue reading incrementing count 
    }

    if(INIT == erFlag) // check whether the loop finishes successfully or a non-int caused it to break
    {
        if( count < 40) // checking whether number of ints less than 40
            erFlag = LESS_40; // 
        else
            if(count > 40) // or more than 40
                erFlag = MORE_40;
    }

    // printing the error
    switch(erFlag)
    {
        case LESS_40:
            cout << "Error: less than 40 integers << endl"; 
        break;
        case MORE_40:
            cout << "Error: More than 40 integers << endl"; 
        break;
        case NON_INT:
            cout << "Error: non-intger found!" << endl;
        break;
        default:
            cout << "Undefined Error" << endl;
    }

    in.close();

    std::cout << std::endl;
    return 0;
}

关于c++ - 从文件中读取整数时的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40703987/

相关文章:

c++ - Eigen:编码风格对性能的影响

c++ - 将 boost::function 克隆到一个指针中并使用该指针调用包装函数

c++ - 指向来自 C++ 中另一个文件的结构内部结构的指针

c++ - 非 native 长度的有符号和无符号整数的性能差异

c++ - 私有(private)继承中的对象切片

c++ - QTableWidget 右键单击​​事件的问题

c++ - 意外的 std::io_base::failure 异常

c++ - 在cuda中声明共享内存的大小

c++ 从数组继承 darray

c++ - 对 randomInteger 的 undefined reference