如何在c ++中将文本文件(.txt)传输到数组2D,这是我的源代码
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这样做,我需要你的帮助和建议,请加入我们你的观点
答案 0 :(得分:1)
此解决方案需要C ++ 11 +
如果没有n&amp; m在文件中,您必须假设布局也是2D
一二三 四五六
警告::未经测试的代码。
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());
}
答案 1 :(得分:0)
所以你的意思是你想要读取文件并将内容复制到char Matrix [] [] ??,你可以使用while循环来读取字符,并按行分割每1024字节(1 kb),我的意思是这样做:
#include <fstream.h>
int main()
{
int n=0, m=0, MAX_LINES=1025, i=0, j=0;
char character, Matrix[1024][1025];
fstream file;
file.open("file.txt", ios::in);
while (file.get(character))// loop executes until the get() function is able to read contents or characters from the file
{
Matrix[n][m]=character; // copy the content of character to matrix[n][m], here n is used to work as lines and m as normal arrays.
m++; // finished copying to matrix[n][m] then m++ else the program will overwrite the contents to the same array.
If (m>=1024)// if string[n][m] reached the limit which is 1024.
{
Matrix[n][m]='\0'; //termimate that line
m=0;// start with a new column
if (n<MAX_LINES)// if n is less than 1024 then
n++;// write to a next line because m can support only 1024 chars.
}
}
Matrix[n][m]='\0';// this will terminate the whole string not just one line.
file.close();
for (i=0; i<1025; i++)
{
for (j=0; j<=1024 || Matrix[i][j]!='\0'; j++)
cout<<Matrix[i][j];
}
return 0;
}
此代码将读取1024×1024个字符,但如果txt文件小于1024(m)个字符,则将退出while循环并且Matrix [n] [m] ='\ 0';声明已经执行。
编辑:正如大卫所说,我用main()编写了整个代码,对不起,我忘了,代码中的错误是变量n和m初始化为1025和1024所以程序跳过写入Matrix作为Matrix [1024] [1025]无法存储更多字符......我认为这会有所帮助,好吧兄弟......