Archived

This topic is now archived and is closed to further replies.

c_str() never changing

This topic is 5017 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Im workin on a scoreboard type system and have been messing about in console tryin to get something to work. In the final Windows version it will output an image. The problem is the score never increases. The int Blah increases but somewhere along the line it just keeps referring to what the original number was (53 in this case). Any ideas?
#include <iostream>
#include <stdlib.h>
#include <sstream>
using namespace std;

int main()
{

	stringstream ss;
	string String1;
	int Blah = 53;

	ss << Blah;
	ss >> String1;
	char const* String2 = String1.c_str();

	while (true)
	{

		cout << String2[0] << String2[1] << endl;

		Blah++;
		ss << Blah;
		ss >> String1;
		String2 = String1.c_str();

	}
  
  system("PAUSE");
  return 0;

}
 

Share this post


Link to post
Share on other sites
I think what your program does is to

add 53 to ss, ss is now "53"

and the loop goes;
add 54 to ss, ss is now "5354"
add 55 to ss, ss is now "535455"
add 56 to ss, ss is now "53545556"
and so on...

this might work:

#include <iostream>
#include <stdlib.h>
#include <sstream>

using namespace std;

int main()
{
int Blah = 53;
while (true)
{
stringstream ss;
ss << Blah;
Blah++;
cout << ss.str()[0] << ss.str()[1] << endl;
}

system("PAUSE");

return 0;
}


PS.
std::stringstream has a function calld str() to return a std::string

std::string has the [] overloaded

one thought that occured to me though is... if blah becomes 123 or 1234 you're only gonna print out 1 and 2; 12. you can always use a for-loop and iterators to run through all letters in a std::string

}-- Programmer/Gamer/Dreamer --{

I didn't choose to code, coding choose me.

[edited by - Seriema on March 17, 2004 6:29:23 PM]

Share this post


Link to post
Share on other sites