c++ - 将文本文件读入整数数组

标签 c++ arrays

给定一个包含一些空行的文件,一些行只包含整数,我如何创建一个包含所有整数的数组?我找到了字符串方法,但我需要一个整数列表。我想使用 getline 执行此操作,但 getline 给出了一个字符串“line”

返回文件中整数数量并修改给定数组的非功能性示例:

int getLinesFromFile(string fileName, int arr[], int arrLen) {
    ifstream userFile;
    userFile.open(fileName);
    if (userFile.is_open()) {
        int line;
        int arrCount = 0;
        while (getline(userFile, line)) {
            if (tline.length() != 0 && arrCount < arrLen) {
                arr[arrCount] = line;
                arrCount++;
            }
        }
        return arrCount;
    }

    else {
        return -1;
    }
    userFile.close();
}

最佳答案

您可以只使用 >>> 运算符来读取值。它将忽略值之间的任何空格,包括空行。这是使用它的函数的修改版本:

int getLinesFromFile(std::string fileName, int arr[], int arrLen) {
    std::ifstream userFile(fileName);
    int count = 0;

    while(count < arrLen) {
            int value;
            userFile >> value;

            if (!userFile.good())
                    return -1;

            arr[count++] = value;
    }

    return count;
}

请注意,您无需手动打开和关闭文件,RAII 会为您处理。此外,如果文件无法成功打开,或者在读取文件时发生任何其他错误,userFile.good() 将返回 false,因此您可以使用检测并返回错误。目前尚不清楚您的函数是否应该准确读取 arrLen 值,或者 less 是否也有效。但至少你应该注意不要写超过提供数组的末尾。

关于c++ - 将文本文件读入整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58274809/

相关文章:

c++ - const_cast 不同的行为 : primitive type vs object type

c++ - 如何在 GCC 中抑制 "enumeral and non-enumeral type in conditional expression"警告

python - 替代 Python 中的二维数组

c++ - 为什么这个结构是用字段中已有的数据初始化的?

c++ - C++ 中 64 位整数的奇怪行为

c++ - 在 C++ STL 中将迭代器推进 1

php - 如何在 php 中执行模式为数组的 preg_match?

JAVA-从txt文件中读取整数并计算整数

c++ - 从主线程中的工作线程捕获异常

jquery - 客户端无法解析JSon,什么问题?