I have a program that reads a .DAT file that contains a list of:
removepeer 452
addpeer 6576
removepeer 54245
At some point, it reads out rubbish text: H�
Here is a part of my code where I find fault in:
getline(abc, info, '\n'); //data here displays pretty fine
int count = info.size();
char text[count];
for(int a=0; a<count; a++){
text[a] = data[a];
}
cout << text << endl; //Some rubbish text found in some printout!
It prints out the last line followed by some rubbish text
The
textarray will not be null terminated, which is required when usingoperator<<withchar[]as they are treated as null terminated c-style strings. Random characters from memory will be written until a null terminator is by chance located. Technically, accessing beyond the bounds of an array is undefined behaviour.To correct, append a null terminator to
text. As your compiler has as an extension for variable length arrays (which are not standard C++, but are in C99) you could change it to:Having said that, I am unsure why you are copying from a
std::stringinstance to achar[].std::stringinstances also be written to streams usingoperator<<.