[英]std::stringstream output does not work the same as std::string
i am currently working on a program whereby i can substitute alphabets in a text file(called plaintext.txt), along with a keyfile, and create a ciphertext when i run a command to mix them together.我目前正在开发一个程序,通过该程序,我可以替换文本文件(称为纯文本.txt)中的字母以及密钥文件,并在运行命令将它们混合在一起时创建密文。 The working code is as shown below:工作代码如下所示:
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;
Output for the above code will be below上面代码的输出将在下面
fgaam
hello
However, i want to convert my "text" and "cipherAlphabet" into a string where i obtain the both of them through different text files.但是,我想将我的“文本”和“密码字母表”转换成一个字符串,在那里我通过不同的文本文件获取它们。
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;
However if i do this, i get no output and no error?但是,如果我这样做,我没有输出也没有错误? Is there anyone out there that can help me with this please?有没有人可以帮我解决这个问题? Thank you!!谢谢!!
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
When you use the above lines of code to extract text
, you are getting any whitespace characters in the file too -- most likely a newline character.当您使用上述代码行提取text
,您也会在文件中获得任何空白字符——很可能是换行符。 Simplify that block of code to:将该代码块简化为:
std::ifstream u("plaintext.txt");
u >> text;
Same change needs to be done to read the cipher.需要进行相同的更改才能读取密码。
If you need to include the whitespaces but exclude the newline character, use std::getline
.如果您需要包含空格但排除换行符,请使用std::getline
。
std::ifstream u("plaintext.txt");
std::getline(u, text);
If you need to be able to deal with multiline text, you will need to change your program a bit.如果您需要能够处理多行文本,则需要稍微更改您的程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.