2016-11-22 88 views
0

我試圖做一個代碼,它會改變文件中的給定單詞,並將其更改爲另一個單詞。該程序的工作方式是逐字複製,如果它是正常的話,它只是將它寫入輸出文件,如果它是我需要更改它的那一個,寫入我需要更改的那個。但是,我已經遇到了一個問題。程序不會將空格放入輸入文件中。我不知道這個問題的解決方案,我不知道我是否可以使用noskipws,因爲我不知道文件在哪裏結束。從文件中讀取而不跳過空格

請記住我是一個完整的新手,我不知道事情是如何工作的。我不知道標籤是否足夠明顯,所以我會再次提及我使用C++

+0

看到輸入修改['noskipws'](http://en.cppreference.com/w/CPP/IO/MANIP/skipws)。 –

+1

顯然,你*知道你何時到達文件結尾:讀取另一個字符或單詞的嘗試失敗。 –

+0

當我使用'noskipws'時,'eof()'不起作用。但我想我不應該用它來檢查文件是否已經結束 –

回答

0

由於每個單詞的讀取都以空格或文件結尾結束,因此您可以簡單地檢查是否停止您的閱讀是文件結尾或其他空白:

if (reached the end of file) { 
    // What I have encountered is end of file 
    // My job is done 
} else { 
    // What I have encountered is a whitespace 
    // I need to output a whitespace and back to work 
} 

而這裏的問題是如何檢查eof(文件結束)。 由於您使用的是ifstream,所以事情會非常簡單。 當ifstream到達文件末尾(所有有意義的數據都已被讀取)時,ifstream :: eof()函數將返回true。 假設您擁有的ifstream實例稱爲輸入。 PS:ifstream :: good()在到達eof或發生錯誤時將返回false。檢查input.good()== false是否可以是更好的選擇。

+0

建議使用「if(!input)」而不是「if(input.eof()== true)」進行測試,因爲流中的錯誤多於文件尾。只需測試EOF就可以讓代碼進入無限循環的不良讀取。 – user4581301

+0

我怎麼知道它是空白還是換行符? –

+0

檢查輸入比eof()好,和good()相同。雖然使用ifstream作爲條件可能會讓初學者感到困惑。 – felix

0

首先,我建議你不要在相同的文件中讀取和寫入(至少在讀取過程中不要讀寫),因爲這會讓你的程序更難寫入/讀取。

其次,如果你想閱讀所有的空格,最簡單的方法是用getline()讀整行。

程序,您可以使用修改的話從一個文件到另一個可能類似於以下內容:

void read_file() 
{ 
    ifstream file_read; 
    ofstream file_write; 
    // File from which you read some text. 
    file_read.open ("read.txt"); 
    // File in which you will save modified text. 
    file_write.open ("write.txt"); 

    string line; 
    // Word that you look for to modify.  
    string word_to_modify = "something"; 
    string word_new = "something_new"; 

    // You need to look in every line from input file. 
    // getLine() goes from beginning of the file to the end. 
    while (getline (file_read,line)) { 
     unsigned index = line.find(word_to_modify); 
     // If there are one or more occurrence of target word. 
     while (index < line.length()) { 
      line.replace(index, word_to_modify.length(), word_new); 
      index = line.find(word_to_modify, index + word_new.length()); 
     } 

     cout << line << '\n'; 
     file_write << line + '\n'; 
    } 


    file_read.close(); 
    file_write.close(); 
} 
相關問題