gpt4 book ai didi

c++ - 如何在 C++ 中将文本文件传输到二维数组?

转载 作者:太空宇宙 更新时间:2023-11-04 11:25:50 24 4
gpt4 key购买 nike

如何在 C++ 中将文本文件 (.txt) 传输到二维数组,这是我的源代码

fstream fin('textfile.txt', ios::in);
int matrix[n][m]; // n is the number of rows and m is the number of columns
for(int i = 0;i < n; i++){
for(int j = 0; j<m; j++){
fin>>matrix[i][j];
}
}

但是我怎样才能确定 n 和 m 来做这件事,我需要你的帮助和建议,请加入我们你的观点

最佳答案

此解决方案需要 C++11+

如果文件中没有n&m,则必须假设布局也是二维的

One Two Three
Four Five Six

警告::未经测试的代码。

std::stringstream res;
std::string wordUp;
std::vector<std::string> str;

// the matrix, vector of vector of strings.
std::vector<std::vector<std::string>> matrix;

fstream fin('textfile.txt', ios::in);
int lines = 0;
int words = 0;

// read the file line by line using `getline`
for (std::string line; std::getline(fin, line); ) {
++lines;
// use stringstream to count the number of words (m).
res.str(line); // assign line to res. might also need some reset of good().
while (res.good()) {
res >> wordUp;
str.push_back(wordUp);
++words;
}
matrix.push_back(str);
str.erase(str.begin());
}

关于c++ - 如何在 C++ 中将文本文件传输到二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26720064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com