char[]混乱的输出

char[] messy output

本文关键字:输出 混乱 char      更新时间:2023-10-16

我创建了一个将int映射到char的映射。0-25到字母a-z和26-35 0-9。

for(int i = 0; i<26; i++)
{
    letters.insert(Match::value_type(i,static_cast<char>(letter + x)));
    x++;
}
for(int i = 26; i<36; i++)
{
    letter = '0' + a;
    letters.insert(Match::value_type(i,letter));
    a++;
}

这里i输入包含数字的pin[]并查找该值。

std::map<int, char >::const_iterator it1 = letters.find(pin[0]);
std::map<int, char >::const_iterator it2 = letters.find(pin[1]);
std::map<int, char >::const_iterator it3 = letters.find(pin[2]);
std::map<int, char >::const_iterator it4 = letters.find(pin[3]);
char fourth  = it4->second;
char third   = it3->second;
char second  = it2->second;
char first   = it1->second;
char combo[] = { first, second, third, fourth};
cout << combo << endl;

一切都很好,但我的cout<< combo给了我"abcd"我不明白为什么。。。我只想在输出中输入"abcd"我该如何清理它。

您需要null终止您的字符串才能在C样式模式中使用它。因此,这将更改为:

char combo[] = { first, second, third, fourth, ''};

现在,您将在fourth之后输出内存中的垃圾,直到找到null字符为止。

char combo[] = { first, second, third, fourth};

定义一个数组,该数组包含4个字符的序列,但不包含可以打印的以null结尾的字符串。执行cout << combo时,输出流将此数组视为公共数组
C样式字符串,即它尝试打印所有字符,直到到达''。尝试:

char combo[] = { first, second, third, fourth, ''};