Pregunta

So I've implemented the Longest Common Subsequence algorithm for the Introduction to Algorithms book (CLRS) in C++, and it works fine, kinda. When I do something like this:

./lcs abc bc > OUTPUT

When I open the OUTPUT file in vim, I see this:

2 bc^@

Which is correct, sans that weird ^@ symbol. I did some Googling and this appears to be some sort of NULL character?

I've never run into this problem before.. anyone know how to get rid of it?

Thanks! -kstruct

EDIT Here's the code that does the printing:

cout << lcsLength << " ";
    if (lcsLength > 0) cout << lcsString;

return 0;

Where lcsString is a std::string. Not sure if that helps...

¿Fue útil?

Solución

You've shown the code that outputs lcsString, but unlike a C style string, a std::string type can contain null characters since the length is maintained separately from the string data itself.

Try adding the following to dump the contents of the string:

cout << "length of lcsString: " << lcsString.length() << endl;
cout << '"' << lcsString << '"' << endl;
for (int i = 0; i < lcsString.length(); ++i) {
    cout << hex <<  int(lcsString[i]) << " ";
}
cout << endl;

I'll bet you will see:

length of lcsString: 3
"bc "
62 63 0 

Then you'll need to find out what you're doing to create (or modify) lcsString such that it contains a null character at the end.

Otros consejos

That's NUL (which is a character value, and is defined to be all-bits-zero), not NULL (which is a pointer, almost always also all-bits-zero, but not required to be).

We're gonna need to see your code to know for sure, but the most likely cause of this is that you printed one more byte of a C-string (which always has NUL as its very last byte) than you should have.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top