C++ std::stringstream输出与std::string的工作原理不同

C++ std::stringstream输出与std::string的工作原理不同,c++,c++11,stringstream,C++,C++11,Stringstream,我目前正在开发一个程序,通过该程序,我可以将文本文件(称为plaintext.txt)中的字母与密钥文件一起替换,并在运行命令将它们混合在一起时创建密文。工作代码如下所示: string text; string cipherAlphabet; string text = "hello"; string cipherAlphabet = "yhkqgvxfoluapwmtzecjdbsnri"; string cipherText; string plainText; bool encip

我目前正在开发一个程序,通过该程序,我可以将文本文件(称为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;
但是,我想将“text”和“cipheraphabet”转换成一个字符串,通过不同的文本文件获取它们

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::ifu流(“plaintext.txt”)//从plainfile.txt获取内容,字符串为文本
std::stringstream纯文本;
明文
读取密码也需要做同样的更改

如果需要包含空格但不包含换行符,请使用
std::getline

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

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

在读取前始终检查
If(t)
,以查看状态是否仍然良好。您没有读取文件。只需将该文件读入std::string并完成它。您可以用谷歌搜索方式。@AnonMail OP正在使用
rdbuf()
@RickAstley my bad读取文件。但是为什么要将它读入std::stringstream?
rdbuf()
会给您一个指向
filebuf
的指针。请继续阅读。谢谢您的快速回复!但是,我想利用函数读取字符串之间空格的能力。现在,我只是试着用文本文件中的一行字符串来阅读。以前,我在使用while和for循环读取文本文件中的空格时遇到了一些困难,我遇到了这种不使用循环读取文本文件的情况。@fabian,在这种情况下,您需要使用
std::getline
<代码>标准::getline(u,文本)。这将包括任何空格,但不包括结束换行符。
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 u("plaintext.txt");
u >> text;
std::ifstream u("plaintext.txt");
std::getline(u, text);