首页 > 解决方案 > 在 C++ 中从 test.txt 中读取信息

问题描述

我正在尝试从 C++ 中的文本文件中读取测试工具。这个想法是我必须读入 5 个 dice 值并将其放入一个数组中,然后读入一个字符串,运行程序,然后再读入 5 个 dice 值并将它们放入一个数组中,然后读入一个字符串,然后运行程序等。

文本文件如下所示:

1 1 2 1 1 Aces
2 2 4 5 6 Twos
3 3 3 2 2 FullHouse
1 2 3 4 4 SmallStraight
2 3 4 5 6 LargeStraight
6 6 6 6 6 Sixes

使用 ifstream 在文件中搜索 1 1 2 1 1 并将这些值放入数组中的最佳方法是什么,然后将“Aces”读入字符串,然后转到下一行并对值 2 2 4 5 6 和字符串“Twos”。

标签: c++

解决方案


我只是想我会帮助你并给你整个解决方案。你让我想起了我刚开始时的自己。我也发表了一些评论。

您可以在此处阅读有关 c++ 文件处理的更多信息。

#include <iostream>
#include <string>
#include <vector>
#include <fstream>


// Struct to hold each "line" of the data.
struct Info {
    static const size_t DICE_LENGTH = 5;

    int dice_values[DICE_LENGTH];
    std::string description;
};


/**
 * @brief Creates the sample file (assuming it doesn't already exist)
*/
void createFile() {
    std::ofstream file ("file.txt");

    if (file.is_open()) {
        file << "1 1 2 1 1 Aces\n";
        file << "2 2 4 5 6 Twos\n";
        file << "3 3 3 2 2 FullHouse\n";
        file << "1 2 3 4 4 SmallStraight\n";
        file << "2 3 4 5 6 LargeStraight\n";
        file << "6 6 6 6 6 Sixes";
    }
    else {
        throw "Error creating file";
    }
}

int main()
{
    createFile();

    std::vector<Info> data;
    std::ifstream file("file.txt");

    if (file.is_open()) {
        Info info;

        while (!file.eof()) {
            // read all the dice values (at most = DICE_LENGTH)
            for (size_t i = 0; i < Info::DICE_LENGTH; ++i) {
                file >> info.dice_values[i];
            }


            // read the String
            std::getline(file, info.description);

            data.push_back(info);
        }
    }
    else {
        std::cerr << "Error opening the file for reading.\n";
        return 1;
    }


    // display the data the was read from the file.
    for (const auto &d : data) {
        // Dice values.
        for (const auto &dice : d.dice_values) {
            std::cout << dice << " ";
        }

        // String value.
        std::cout << d.description << std::endl;
    }

    return 0;
}

输出:

1 1 2 1 1 Aces
2 2 4 5 6 Twos
3 3 3 2 2 FullHouse
1 2 3 4 4 SmallStraight
2 3 4 5 6 LargeStraight
6 6 6 6 6 Sixes


推荐阅读