Reputation: 334
The output expected is "2a3b3c4d3l4z" but i'm getting:12a3b3c4d3l4z.
Why the extra "1" is coming in the output?
char ipstr[] = "aabbbcccddddzzzzlll";
cout<<"size of string:"<<sizeof(ipstr)<<endl;
num = 0;
map<char, int> ms;
for(int i = 0; i<sizeof(ipstr);i++){
if(ipstr[i] == ipstr[i+1])
num++;
else{
ms[ipstr[i]] = num+1;
num = 0;
}
}
for(auto it = ms.begin();it != ms.end();it++){
cout<<it->second<<it->first;
}
cout<<endl;
Upvotes: 1
Views: 87
Reputation: 1006
You evaluated your string length including '\0' character (it can be ambigious that string ends with this one). Then in a for loop you added '\0' to the map. But what does it mean to print null character. That's why you have 1 and a whitespace at the beginning.
char ipstr[] = "aabbbcccddddzzzzlll";
int n = strlen(ipstr);
cout << "size of string:" << n << endl;
int num = 0;
map<char, int> ms;
for (int i = 0; i < n - 1; i++) {
if (ipstr[i] == ipstr[i + 1])
num++;
else {
ms[ipstr[i]] = num + 1;
num = 0;
}
}
for (auto it = ms.begin(); it != ms.end(); it++) {
cout << it->second << it->first;
}
cout << endl;
Upvotes: 2
Reputation: 5026
The extra 1
is the printout of the entry {'\0', 1}
caused by taking the trailing '\0'
into the loop. The \0
is not printable, therefore you see only 1
.
Upvotes: 2