所以我有一个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];
}
}
}
答案 0 :(得分:2)
我想我明白你的意思。您希望将文件的所有行都放入一个数组。但也希望能够通过将其放入向量中来访问该行的每个部分(由空格分隔)。
代码:
#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;
请注意,当然零索引。