Мне кажется, я понимаю, что вы имеете в виду. Вы хотите, чтобы все строки вашего файла были в массиве. Но также нужно иметь возможность получить доступ к каждой части - разделенной пробелом - этой строки, поместив ее в вектор.
Код:
#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
Вы можете получить доступ к определенным c частям вашего файла, используя индексы вектора. Если вы хотите, например, распечатать 'ddd', который находится на четвертой строке второй части. Вы используете:
//Access 'ddd' (line 4 second part)
std::cout << myVector[3][1] << std::endl;
Помните о нулю, конечно же, обнуление.