2017-10-18 56 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

相关问题