2014-11-03 75 views
1

我如何可以將C++中的文本文件(.txt),以陣列2D,這是我的源代碼如何在C++中將文本文件傳輸到數組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]; 
    } 
} 

但我怎麼能detemine n和m爲做到這一點,我需要您的幫助和建議請加入我們您的觀點

+1

我很想加入我的觀點,並加入你的所有,但這取決於數據如何佈局文本文件。發佈樣本。 – 2014-11-03 17:57:05

+0

'std :: vector'? – clcto 2014-11-03 17:59:16

+0

@MarcoA。我不知道這意味着什麼,但我喜歡它 – 2014-11-03 18:00:32

回答

1

該解決方案需要C++ 11 +

如果在文件中不適用&男,你必須假設的佈局也是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()); 
} 
+0

非常感謝你有趣的回答 – David 2014-11-07 10:16:24

0

所以ü意味着ü要讀取文件和複製內容到char矩陣[] [] ??,你可以使用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';語句被執行。

編輯:正如大衛問我寫的整個代碼與主()對不起兄弟我忘了,代碼中的錯誤是變量n和m初始化到1025和1024,所以程序跳過寫入矩陣作爲矩陣[1024] [1025]不能存儲更多的字符...我認爲這會有所幫助,好的兄弟...

+0

看我不明白我應該從這個問題(堆棧交換)瞭解什麼是你製作有趣的是,你的編譯器告訴你,堆棧交換的代碼不會編譯?好吧,我無法清除更多,你必須在代碼審查網站上發佈該程序,他們會幫助你確保兄弟... – Rishabh 2014-11-09 06:53:54