MMS
MMS

Reputation: 404

Standard Stream Printing Unrelated Characters

I was coding something and my code didn't work correctly in some situations, so I decided to write some output to file for debugging. The program just concatenates some characters from a string (and it didn't get out of bounds) and printed them to the file. It has no thing as error reporting or something, and the input string is just a bunch of random characters. But, i get some junk in the output, such as:

f::xsgetn error reading the file
sgetn error reading the file
ilebuf::xsgetn error reading the file

(I removed program's output and this is just the extra stuff.)

As far as I know, if there are any errors, an exception must be thrown. What happens and how can I fix it?

The same thing happens when I print the output using standard output. All used libraries are standard libraries (eg. iostream, fstream, etc.)

PS: For some reasons, I can't publish all the code. Here is the part that creates the output and passes it to stream: (tri is and string, and is defined previously. Center is an integer and is inside the bounds of the string. fout is a previously defined file stream.)

string op = "" + tri[center];
fout << center << "<>" << op << endl;

Upvotes: 3

Views: 138

Answers (2)

MMS
MMS

Reputation: 404

I encountered the same problem in another program, where I had written:

str += blablabla + "#";

and I saw some unrelated characters being printed. I fixed it this way:

str = str + blablabla + "#";

and it worked!

There is some problem with the += operator for string.

Upvotes: 1

molbdnilo
molbdnilo

Reputation: 66431

Since tri is a string, tri[center] is a char.
The type of "" is const char[], which can't be added to a char.
Instead it is implicitly converted to const char*, which can be added to a char.

Unfortunately for you, the result of that is that the integer value of tri[center]is added to that pointer as an offset, not as a string concatenation, and the particular area of memory that the result refers to doesn't contain what you're looking for but instead contains other static strings like e.g. "error reading the file".

To fix it, use

string op = string("") + tri[center];

instead.

Upvotes: 1

Related Questions