std::stringstream 输出与 std::string 不同

std::stringstream output does not work the same as std::string

我目前正在开发一个程序,通过该程序我可以替换文本文件(称为 plaintext.txt)中的字母以及密钥文件,并在 运行 命令混合时创建密文他们在一起。工作代码如下所示:

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

但是,我想将我的 "text" 和 "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;

但是如果我这样做,我没有输出也没有错误?有没有人可以帮我解决这个问题?谢谢!!

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);

如果您需要能够处理多行文本,则需要稍微更改您的程序。