首页 > 解决方案 > 如何初始化整数 + 字符串数组

问题描述

我是 C++ 新手,需要帮助!我目前正在学习如何制作二维数组或一维数组。

我有一个文本文件,其内容如下所示,我基本上是在尝试将它们存储到一个数组或更多取决于?如果我使用 Struct,或者基于下面文件中的内容,我只能拥有 1 个数组,或者 5 个单独的数组,是真的吗?

我相信 [1, 2] 可以形成一个二维数组,但是我该如何实现呢?

下面是我使用结构的代码,我不确定我做对了吗?

请帮忙!

=========================================================
Sample Contents in 'HelloWorld.txt' File
=========================================================
[1, 2]-3-4-Hello_World
[5, 6]-7-8-World_Hello
[9, 1]-2-3-Welcome_Back
[4, 5]-6-7-World_Bye
[8, 9]-1-2-Bye_World

=========================================================
My Sample Codes
=========================================================
struct Example()
{
    fstream file;
    file.open("HelloWorld.txt");

    vector<string> abc; 
    string line;

    while(getline(file, line, '-'))
    {
        abc.push_back(line);

        int** a = new int*[abc.size()];
        for(int i = 0; i < abc.size(); i++)

        cout << abc[i] << endl;

        delete [] a;
    }
}

我的主要目标是能够将所有 4 个整数 + 1 个字符串存储到数组中,并学习如何使用 '[1, 2]' -> 前两个整数点创建一个二维数组。

等待建议!谢谢!

标签: c++arraysc++11multidimensional-arraydelimiter

解决方案


首先,使用 c++ 特性和数据结构。您可以使用向量而不是数组,它更安全且易于使用。其次,您不必使用二维数组,您可以使用向量的一维数组。我们的数据结构是您的结构向量的向量,您可以读取文件并使用这些值创建一个结构,然后放入向量中。

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

struct MyData
{
    MyData():
        num1(0),
        num2(0),
        num3(0),
        num4(0),
        str("")
    { }

    int num1;
    int num2;
    int num3;
    int num4;
    std::string str;
};


void ReadFile(std::vector<MyData>& myVec)
{
    std::string fileName = "HelloWorld.txt";
    std::ifstream file(fileName, std::ios::binary);

    if (file.fail())
    {
        std::cout << "Error while reading";
        perror(fileName.c_str());
    }

    std::string line;
    while (std::getline(file, line))
    {
        //parse this line
        // store suitable values to the struct
        // MyData myStruct;
        // myStruct.num1 = ...
        // myStruct.num2 = ...
        // myStruct.num3 = ...
        // myStruct.num4 = ...
        // myStruct.str = ...
        //myVec.push_back(myStruct);
        // or you can directly use emplace_back that is more efficent
        // but is more complicated for you now..
        // you can practice...
    }
}

int main()
{
    std::vector<MyData> myVector;
    ReadFile(myVector);
    return 0;
}

推荐阅读