1

我创建了一个将 int 映射到 char 的映射。0-25 到字母 az 和 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[[[[[a[[[[[b[[[[c[[[[[d]]]]]pPP”。我不明白为什么......我在输出中想要的只是“abcd”我该如何清理它。

4

2 回答 2

2

您需要空终止您的字符串才能在 C 样式模式下使用它。所以这将变为:

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

现在,您正在输出内存中的垃圾,fourth直到null找到一个字符。

于 2013-03-07T00:01:14.760 回答
1
char combo[] = { first, second, third, fourth};

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

char combo[] = { first, second, third, fourth, '\0'};
于 2013-03-07T00:00:55.150 回答