Bryan Wong
Bryan Wong

Reputation: 633

Reading characters displays all characters followed by some rubbish characters

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

Upvotes: 0

Views: 64

Answers (1)

hmjd
hmjd

Reputation: 122001

The text array will not be null terminated, which is required when using operator<< with char[] 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:

char text[count + 1];

// snip...

text[count] = 0;

Having said that, I am unsure why you are copying from a std::string instance to a char[]. std::string instances also be written to streams using operator<<.

Upvotes: 4

Related Questions