2013-03-06 123 views
0

我已经创建了一个将int映射到char的映射。 0-25字母a-z和26-35 0-9。char []凌乱输出

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 [[[[[一个[[[[[B [[[[C [[[[[d]]]]] PPP”。 我不明白为什么......所有我想在输出中只是“abcd”我该如何清理它。

+5

null终止符。 – 2013-03-06 23:58:55

+0

对不起。由于某种原因它被切断了,但这里是 – user1665569 2013-03-06 23:59:02

+0

我不明白@JesseGood。我的组合是空的? – user1665569 2013-03-07 00:01:41

回答

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

定义包含的4个字符序列的阵列,但不是一个空终止字符串可能被打印出来。当cout << combo正在执行时,输出流将此数组视为通用的
C样式字符串,即它会尝试打印所有字符,直到达到'\0'。尝试:

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

您需要空终止你的字符串能在C风格的方式来使用它。因此,这将改变为:

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

现在你outputing直到null字符是你在内存fourth后的垃圾。