2010-04-01 156 views
5

我正在將文件讀入數組。它正在讀取每個字符,出現問題的原因是它也在文本文件中讀取換行符。需要跳過輸入文件中的換行字符( n)

這是一個數獨板,這裏是我的代碼在字符閱讀:

bool loadBoard(Square board[BOARD_SIZE][BOARD_SIZE]) 
{ 
    ifstream ins; 

    if(openFile(ins)){ 

    char c; 

    while(!ins.eof()){ 
     for (int index1 = 0; index1 < BOARD_SIZE; index1++) 
     for (int index2 = 0; index2 < BOARD_SIZE; index2++){ 
      c=ins.get(); 

      if(isdigit(c)){ 
      board[index1][index2].number=(int)(c-'0'); 
      board[index1][index2].permanent=true; 
      } 
     } 
    } 

    return true; 
    } 

    return false; 
} 

就像我說的,它會讀取文件,顯示在屏幕上,只是沒有在正確的順序,當它遇到\ n

+0

標籤問題作爲家庭作業,如果它是一門功課的問題。 – wilhelmtell 2010-04-01 01:16:31

回答

0

那麼在你的文件格式中你可以不保存換行符,或者你可以添加一個ins.get()for循環。

你也可以將你的c = ins.get()包裝在一個類似getNextChar()的函數中,它將跳過任何換行符。

我想你想是這樣的:

for (int index1 = 0; index1 < BOARD_SIZE; index1++) 
{ 
    for (int index2 = 0; index2 < BOARD_SIZE; index2++){ 

    //I will leave the implementation of getNextDigit() to you 
    //You would return 0 from that function if you have an end of file 
    //You would skip over any whitespace and non digit char. 
    c=getNextDigit(); 
    if(c == 0) 
    return false; 

    board[index1][index2].number=(int)(c-'0'); 
    board[index1][index2].permanent=true; 
    } 
} 
return true; 
+0

你能更具體一點嗎?這裏幾乎是一個n00b。 也許我沒有解釋自己 - 我需要它跳過新行,只要它遇到它,而不是寫它到數組元素... – codefail 2010-04-01 00:43:08

+0

@igor:是的我會但我有一個問題首先,每行之後的文件是否有換行符? – 2010-04-01 00:43:56

+0

是的,但我想(因爲這將發送給「autograder」)換行符可以在任何地方? 但是當然,讓我們只在每一行後面加一個換行符。 – codefail 2010-04-01 00:45:24

2

你可以把你ins.get()在do while循環:

do { 
    c=ins.get(); 
} while(c=='\n'); 
0

你有幾個不錯的選擇。要麼不要將換行符保存在文件中,要麼在循環中明確丟棄它們,要麼在<string>中使用std::getline()

例如,使用getline()

#include <string> 
#include <algorithm> 
#include <functional> 
#include <cctype> 

using namespace std; 

// ... 

string line; 
for (int index1 = 0; index1 < BOARD_SIZE; index1++) { 
    getline(is, line); // where is is your input stream, e.g. a file 
    if(line.length() != BOARD_SIZE) 
     throw BabyTearsForMommy(); 
    typedef string::iterator striter; 
    striter badpos = find_if(line.begin(), line.end(), 
          not1(ptr_fun<int,int>(isdigit))); 
    if(badpos == line.end()) 
     copy(board[index1], board[index1]+BOARD_SIZE, line.begin()); 
} 
相關問題