a little problem w/ c++ strings

Started by
3 comments, last by zerovoid 24 years, 5 months ago
The line "while (x < string::npos)"... shouldn't that really be "while (x > string::npos)"... if you're using STL, npos is -1, and the smallest x could ever be is 0, so I can't see how the code as you've written it would even enter the while loop at all.

Is that a typo, or am I missing something?

Mason McCuskey
Spin Studios
www.spin-studios.com

Founder, Cuttlefish Industries
The Cuttlefish Engine lets anyone develop great games for iPad, iPhone, Android, WP7, the web, and more!
Advertisement
as far as i know, npos is part of the c++ string class and has nothing to do with the STL. npos is just the end of the string, and it enters the loop fine, and for some reason, i can get it to execute the text.replace(x, y-x+1, s) once, but after that it hangs the program, so i'm not sure exactly what to think.
Are you sure "text" is terminated with a '\n'? Otherwise the for loop will not terminate for some time. In fact, you should get a GPF. Consider a string that looks like this.

I am a fish.\n
// I am a comment.

After the first two lines, x will point to the first slash and y will equal string::npos. Remember that y will never equal -1, because you're using unsigned integers.

Would someone be so friendly as to tell me why they think this code when compiled and ran, causes the program to go on forever?

x = text.find( "//" );
y = text.find( "\n", x + 2 );

while( x < string::npos )
{
for( unsigned int z = x; z <= y; z++ ) s += text[z];

s = GetTextLine( s, COMMENT_COLOR );
text.replace( x, y-x+1, s );

s = "";
x = text.find( "//", y + 1 );
y = text.find( "\n", x + 2 );
}

btw, this is just the snippet causing it, and if i comment out the line 'text.replace( x, y-x+1, s);' everything works fine...

any input on the matter would be very much appreciated

oi oi

after many hours trying to get this to work, i finally found the problem... on the for loop, i was including one character too many for the new string 's', i was making it end after the newline, instead of before, so i changed that, and it works perfectly now... its funny how such a time-consuming problem can be traced to a miscalculation of 1

thanks for respond though...

This topic is closed to new replies.

Advertisement