2017-10-18 124 views
-1

我目前正在一個程序,我可以在一個文本文件(稱爲plaintext.txt),以及一個密鑰文件中替換字母,並創建一個密文當我運行一個命令將它們混合在一起。工作代碼如下所示:std :: stringstream輸出不工作相同std ::字符串

string text; 
string cipherAlphabet; 

string text = "hello"; 
string cipherAlphabet = "yhkqgvxfoluapwmtzecjdbsnri"; 

string cipherText; 
string plainText; 

bool encipherResult = Encipher(text, cipherAlphabet, cipherText); 
bool decipherResult = Decipher(cipherText, cipherAlphabet, plainText); 

cout << cipherText; 
cout << plainText; 

輸出上面的代碼將低於

fgaam 
hello 

不過,我想我的「文本」和「cipherAlphabet」轉換成在那裏我得到的字符串他們兩人通過不同的文本文件。

string text; 
string cipherAlphabet; 


std::ifstream u("plaintext.txt"); //getting content from plainfile.txt, string is text 
std::stringstream plaintext; 
plaintext << u.rdbuf(); 
text = plaintext.str(); //to get text 


std::ifstream t("keyfile.txt"); //getting content from keyfile.txt, string is cipherAlphabet 
std::stringstream buffer; 
buffer << t.rdbuf(); 
cipherAlphabet = buffer.str(); //get cipherAlphabet;*/ 

string cipherText; 
string plainText; 

bool encipherResult = Encipher(text, cipherAlphabet, cipherText); 
bool decipherResult = Decipher(cipherText, cipherAlphabet, plainText); 

cout << cipherText; 
cout << plainText; 

但是,如果我這樣做,我得到沒有輸出,沒有錯誤?有沒有人可以幫我解決這個問題?謝謝!!

+0

在從中讀取數據以查看狀態是否仍然良好之前,請務必檢查「if(t)」。 –

+0

您沒有閱讀文件。只需將文件讀入std :: string並完成它即可。你可以谷歌如何。 –

+0

@AnonMail OP實際上是使用'rdbuf()'讀取文件。 –

回答

1
std::ifstream u("plaintext.txt"); //getting content from plainfile.txt, string is text 
std::stringstream plaintext; 
plaintext << u.rdbuf(); 
text = plaintext.str(); //to get text 

當你使用上面的代碼行提取text,你所得到的文件中的任何空白字符太 - 最有可能的一個換行符。簡化該代碼塊:

std::ifstream u("plaintext.txt"); 
u >> text; 

讀取密碼需要做相同的修改。

如果您需要包含空格但排除換行符,請使用std::getline

std::ifstream u("plaintext.txt"); 
std::getline(u, text); 

如果您需要能夠處理多行文本,你將需要改變你的程序了一下。

+0

感謝您的快速回復!但是,我想利用函數的能力來讀取字符串之間的空格。 現在,我只是嘗試閱讀文本文件中的一行字符串。我在使用while和for循環之前閱讀文本文件中的空格時遇到了一些困難,並且我在不使用循環的情況下發現了文本文件的讀取。 – fabian

+0

@fabian,在這種情況下,你需要使用'std :: getline'。 'std :: getline(u,text);'。這將包括任何空格,但不包括結尾換行符。 –

+0

哦,我的上帝像魅力一樣工作!非常感謝你的幫助!!! :D – fabian

相關問題