2014-12-06 205 views
0

我試圖寫一個程序: -reads一個文本文件,然後把它轉換成字符串 -change每個字母在字符串中減去4 -outputs在修改行讀取文件到程序

我知道如何輸入/輸出文件。我沒有比這更多的代碼,因此對我來說這是一個非常新的概念。我已經研究過,找不到直接的答案。如何將原始文件的每一行輸入到一個字符串中然後進行修改?

謝謝!

// Lab 10 
// programmed by Elijah 

#include <iostream> 
#include <string> 
#include <fstream> 
using namespace std; 


int main() 
{ 
    fstream dataFile; 
//Set the file "coded" as the line input 
    dataFile.open("coded.txt", ios::in); 

//Create the file "plain2" as program output 
    dataFile.open("plain2.txt", ios::out); 

} 

回答

1
#include <iostream> 
#include <string> 
#include <fstream> 
using namespace std; 
int main() 
{ 
    ifstream inFile ("coded.txt"); //explicitly input using ifstream rather than fstream 
    ofstream outFile ("plain2.txt"); //explicitly output using ofstream rather than fstream 
    string str = ""; 
    char ch; 
    while (inFile.get(ch)) 
    { 
     if (ch!='\n' && ch!=' ') 
     { 
      //do your manipulation stuff //manipulate the string one character at a time as the characters are added  
     }str.push_back(ch); //treat the string as an array or vector and use push_back(ch) to append ch to str 
    } 
} 

這更明確地打開輸入和輸出文件流,然後創建一個空字符串和單位字符。 inFile.get(ch)只要不在文件末尾就會返回true,並將下一個字符分配給ch。然後在循環中,您可以使用ch做任何您需要的操作。我只是將它附加到字符串中,但聽起來好像在追加之前你會想做點什麼。 (ch)會比getline()或>>方法更好,因爲get(ch)也會添加空格,製表符和其他特殊字符,它們是getline()文件的一部分,而>>會忽略。

如果字符串4你的意思是在操縱線4少的字符,你可以使用:

ch = ch-4; 

注意,這可能得出的結果比預期的不同,如果通道最初是「A」 ,'b','c'或'd'。如果你想環繞使用ascii操作和模運算符(%)。

+0

謝謝,這個作品很棒!一個問題:是否有辦法維護原始輸入文件中包含的換行符? – Elijah 2014-12-06 20:14:17

+0

如果你的意思是換行符,我認爲這些將會像任何其他字符一樣存儲到ch中。如果不是,請填寫 – 2014-12-06 21:08:51

+0

@Elijah您可能會無意中通過減去4來修改ch,如果它是換行符或空格,則不會執行此操作。看修改後的答案。 – 2014-12-06 21:19:02