C ++如何处理具有多种数据类型的文件?

C++ how to handle file with multiple data types?

我有一个输入 txt 文件,其中包含如下信息:

    4
    Eric Nandos
    3
    15.00 45.00 36.81 64.55 50.50
    51.52 36.40 25.15 35.45 24.55
    41.55 44.55 36.35 55.50 40.55
    Steven Abraham
    2
    40.45 20.35 40.46 30.35 55.50
    18.25 18.00 20.00 30.00 60.65
    Richard Mccullen
    2
    40.45 50.55 20.45 30.30 20.25
    30.00 20.00 40.00 60.60 45.45
    Stacey Vaughn
    3
    45.00 25.00 15.00 30.30 25.20
    20.20 60.65 55.55 50.50 50.40
    30.30 60.55 20.25 20.00 40.00

使用 getline(file, string) 我可以将这些数据存储到一个字符串变量中,然后将其输出。 问题是,我需要将不同的数据类型存储到不同的变量中,以便对它们进行某些操作(例如:我需要计算十进制值的平均值,添加不同的 int 值,将一些数据存储到向量中,等等)。我尝试了不同的循环来解析文件,但每次都出现错误。关于如何在此处分离不同数据以便我可以相应地存储它们的任何建议?我还是 C++ 的新手,所以我没有太多经验。谢谢。

第一行指定文件中的记录数,其中每条记录包括:

  • 1 行人名

  • 1 行指定后续行数

  • N行浮点数

你可以这样读取这样的数据:

#include <fstream>
#include <sstream>
#include <string>
#include <limits>

...

int numRecords, numLines;
std::string name, line;
double value;

std::ifstream file("filename.txt");
if (!file.is_open()) {
    // error handling...
}

if (!(file >> numRecords)) {
    // error handling ...
}

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

for (int i = 0; i < numRecords; ++i)
{
    if (!std::getline(file, name)) {
        // error handling...
    }

    // use name as needed...

    if (!(file >> numLines)) {
        // error handling...
    }

    for (int j = 0; j < numLines; ++j)
    {
        if (!std::getline(file, line)) {
            // error handling...
        }

        std::istringstream iss(line);
        while (iss >> value) {
            // use value as needed...
        }
        if (iss.fail()) {
            // error handling...
        }
    }
}

您可以使用 std::ifstream0's from <fstream>1
它的工作方式与 std::cin2 完全一样,除了文件。
Example
这是一个实际的实现:Compiler Explorer