如何根据第一个和第三个字符将字符串读入 C++ 中的二维字符串数组

How to read in strings, based upon the first, and then third character, to a 2D string array in C++

所以我有一个 35 行的文本文件,格式如下:

number [space] string [space] number [space] number [newline]

现在我想将该文本文件的内容读入一个数组。但在某种程度上,文件的每一行也以其自己的单独数组表示。从而创建一个二维数组。

伪例子:

myFileContentInArrayFormat = [
    [1, "string", 155 29],
    [2, "aa", 425 96],
    [3, "blabla", 8375 2099]
]

我的尝试如下,显然没有读入正确

    void player::readToArray(ifstream& infile, string filename)
    {
    infile.open(filename);


    for (int i = 0; i < 35; i++)
    {
        for (int e = 0; e < 13; e++)
        {
            infile >> Array[i][e];
        }
    }
}

我想我明白你的意思了。您希望将文件的所有行放入一个数组中。但也希望能够通过将其放入向量中来访问该行的每个部分 - 由 space 分隔。

代码:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
//You probably want to take a look at vectors instead of arrays
#include <vector>

//readToArray
//:param filename: Name of the file to read from
std::vector< std::vector<std::string> > readToArray(std::string filename) {
    //Declaring ifstream here, can be from parameter too like in your code but why would you do that?
    std::ifstream file(filename);
    std::string line;
    std::vector<std::string> fileContent;

    //Check if file succesfully opened
    if (file.is_open()) {
        //Read all the lines and put them in the vector
        while (getline(file, line)) {
            fileContent.push_back(line);
        }

        file.close();
    } else {
        std::cerr << "Error opening file " << filename << std::endl;
    }

    //Now all the lines are in the vector fileContent in string format
    //Now create your two dimensional array (with the help of vectors)
    std::vector< std::vector<std::string> > twoDimensionalVector;

    //Loop over all lines
    for (std::string& line : fileContent) {
        //Splitting the contents of the file by space, into a vector
        std::vector<std::string> inlineVector;
        std::istringstream iss(line);
        for(std::string s; iss >> s; )
            inlineVector.push_back(s);

        //Now push this separated line (which is now a vector to the final vector)
        twoDimensionalVector.push_back(inlineVector);
    }

    //Return
    return twoDimensionalVector;

}

int main() {
    std::string filename = "test.txt";
    std::vector< std::vector<std::string> > myVector = readToArray(filename);

    //Now print out vector content
    for (std::vector<std::string>& vec : myVector) {
        //Print out vector content of the vector in myVector
        std::cout << "[ ";
        for (std::string& str : vec) {
            std::cout << str << " ";
        }
        std::cout << "]" << std::endl;
    }
}

test.txt

1 aaa 67 777
2 bbb 33 663
3 ccc 56 774
4 ddd 32 882
5 eee 43 995

您可以使用向量的索引访问文件的特定部分。例如,如果你想打印出第二部分第四行的 'ddd'。你使用:

//Access 'ddd' (line 4 second part)
std::cout << myVector[3][1] << std::endl;

当然要注意零索引。