2017-05-04 56 views
0

我想從Linux/Mint上的txt文件獲取輸入數據。因此,在編譯代碼之後,我運行以下命令:./a.out output.txt 我需要填充一個二維數組,但像一個鋸齒形數組(每行中的列數不同)。所以我想通過查看字符從文件中讀取什麼來分割它。如果字符是'\ n',我想填寫第二行。但我想我無法讀取'\ n'字符。我希望我能解釋這個問題。 我在寫代碼,也許它會更清晰。如何從輸入文件中獲取字符' n'?

我input.txt的文件是:

enter image description here

我的C++代碼的部分是用於獲取輸入:

for (int i = 0; i<n; i++) { 
    char ch; 
    cin >> ch; 
    int j = 0; 
    while (ch != '\n') { 
     arr[i][j] = ch; 
     cin >> ch; 
     j++; 
    } 
} 

我想的是,如果字符是等於「\ n '然後程序繼續填充數組到下一行。

arr[0][0] = 'a'; 
arr[0][1] = 'f' 
arr[0][2] = 'h' 

arr[1][0] = 'b' 
arr[1][1] = 'e' 
arr[1][2] = 'g' 

arr[2][0] = 'c' .......) 
+0

['getline'](http://www.cplusplus.com/reference/istream/istream/getline/)讀,直到線 – user463035818

+0

不的端部太清楚你想要什麼,但爲什麼不使用std :: get()。 –

+0

我強烈建議你使用'std :: ifstream'來輸入文本文件,而不是'std :: cin'。正如之前所評論的,'getline'是讀取輸入文件的好選擇。 – EuGENE

回答

1

當你做cin >> ch將跳過空白,包括空格,製表符和換行符。也許,您需要使用std::getline來讀取整行,然後分別處理每行。

例如:

#include <iostream> 
#include <sstream> 
#include <string> 

using namespace std; 

int main() 
{ 
    char ch; 
    std::string line; 
    int ln = 0; 
    while (getline(cin, line)) // read entire line 
    { 
     istringstream is; 
     is.str(line); 
     while (is >> ch) // now read individual chars from that line 
      cout << "line: " << ln << " char: " << ch << endl; 
     ln++; 
    } 
} 

而且你的循環應該是這樣的:

std::string line; 
for (int i=0; i<n; ++i) 
{ 
    char ch; 
    if (!std::getline(cin, line)) 
     break; 
    std::istringstream is; 
    is.str(line); 
    for (int j=0; is >> ch; ++j) 
     arr[i][j] = ch; 
} 

你你如何申報您的arr省略細節,但它似乎並不像你的代碼已經顯示會妥善處理它。也許,這將是更好地使用載體:

std::vector<std::vector<char> > arr; 
std::string line; 
char ch; 
while (std::getline(cin, line)) // cin should probably be replaced with ifstream 
{ 
    std::istringstream is; 
    is.str(line); 
    arr.push_back(vector<char>()); 
    for (int j=0; is >> ch; ++j) 
     arr.back().push_back(ch); 
} 
+0

@Bob__是的,OP省略了關於變長數組的部分,我只是假設它可行,因爲問題大部分不是關於如何做「鋸齒狀數組」,而是如何讀取字符並知道何時遇到新行。起初我想評論一下顯示'arr'的定義,但主要是處理輸入。 – Pavel