Reputation: 99
I'm trying to output a 2D int array into a string with this code:
string sGrid;
for(int a=0;a<6;a++){
for(int b=0;b<7;b++)
sGrid+=grid[a][b]+"\t";
sGrid+="\n";
}
when I print this string to cout I get these random characters:
_
.txttxtxtt
¨€+'*€+'*+'*'*'**
*
The grid is filled with:
count=1;
for(int a=0;a<6;a++){
if(bStart){
for(int b=dayOfWeek;b<7;b++){
grid[a][b]=count;
count++;
}
}
else{
for(int b=0;b<7;b++){
grid[a][b]=count;
count++;
if(count>=numOfDays)
break;
}
}
bStart=false;
if(count>=numOfDays)
break;
}
Full source code found here: source code
Upvotes: 0
Views: 219
Reputation: 29055
@0x499602d2's comment is correct, but I think the idiomatic way to do this with C++ is to use stringstreams:
#include <sstream>
std::ostringstream strBuilder;
for(int a=0; a<6; a++) {
for(int b=0; b<7; b++) {
strBuilder << grid[a][b] << '\t';
}
strBuilder << '\n';
}
const std::string sGrid = strBuilder.str();
stringstreams grow in a more performance-friendly way (exponentially, rather than linearly) so this should be faster in addition to being more correct. Your old code (when corrected per 0x499602d2's comment) would have resulted in continual reallocation of buffers large enough to hold just the "current iteration" of the string contents, rather than anticipating growth as a stringstream would.
Upvotes: 1
Reputation: 8942
As somebody mentioned it in the comments, this is because you are adding types that should not be added together. Try this instead:
string sGrid;
for(int a=0;a<6;a++){
for(int b=0;b<7;b++){
sGrid+=grid[a][b];
sGrid+="\t";
}
sGrid+="\n";
}
Upvotes: 0