输入Std::cin与直接赋值Std::string变量不一样

std::cin input not the same as direct assign std::string variable

本文关键字:Std string 变量 不一样 赋值 cin 输入      更新时间:2023-10-16

我有一个奇怪的问题,如果我通过std::cin分配变量,它不同于直接变量分配。例1字符串与例2字符串不相同。

我使用xor解密函数来解密密文。
如果通过std::cin分配变量,则得到正确的输出(Example1)。但是如果我用密文字符串直接赋值变量,我将得到一个不同的输出(Example2)。

std::cin赋值和直接变量赋值有什么不同?

例1:(std::cin)
std::string my_input;
std::cin >> my_input;
输入:

89001 c110704918484dcdcdc85df9b9d8a2310005c08dccad8d7cccec3df824555a6dfced8df0045550输出: http://www.test.de/|是|可以 |½½½½½½½½¯

例二:(直接变量赋值)
std::string my_input;
my_input = "89001c110704918484dcdcdc85df9b9d8a2310005c08dccad8d7cccec3df824555a6dfced8df0045550";
输出:

测试■½½www.test═¯¯oµ"美元,┌©½░½)¯■

如果我只得到一行,输出与直接变量assign相同。但是为什么呢?

std::string my_input;
std::getline(std::cin, my_input);
输入:

89001 c110704918484dcdcdc85df9b9d8a2310005c08dccad8d7cccec3df824555a6dfced8df0045550输出:测试■½½www.test═¯¯oµ"美元,┌©½░½)¯■

我猜一下是什么问题。(这个问题需要更多的细节。)

将示例1代码替换为:

std::string my_input;
std::getline(std::cin, my_input);

现在发生了什么?

假设输入字符串不包含任何空格(这会导致std::cin >> my_input在使用整个字符串之前返回),结果应该是相同的。不是在解密文本后比较结果,而是比较包含密文的两个字符串,例如:

std::string direct_assign;
local = "89001c110704918484dcdcdc85df9b9d8a2310005c08dccad8d7cccec3df824555a6dfced8df0045550";
std::string input;
std::cin >> input;
std::cout << (direct_assign == input) << std::endl;

假设结果字符串是相等的,它们在解密时没有理由表现不同(除非解密函数或它的调用方式有错误)。