I am using C++ and writing a program that is supposed to do a bunch of stuff with primes. However the main issue is that I am having trouble converting in between ints and strings. I believe the following is the relevant code:
for(int j=0;j<size-1;j++){
num=primes[j];
ss<<num;
ss>>temp;
ss.str("");
for (int count=0; count < temp.size(); count++) {
cout<<temp<<endl;
}
I know that I could Google and figure out how to convert from an integer another way. However, I have a feeling that the reason I can’t figure out what is going wrong is because I’m lacking some fundamental knowledge about stringstreams which I’m not aware of which I’m hoping can be fixed. num is an int and ss is a stringstream and cout temp is printing out 2 every single time, which is the value of primes[0]. I think the stringstream might be not reading after the first trial because of something to do with a newline character but I don’t really know.
The reason for what you are experiencing is that the EOF_BIT will be set in
ssafter reading the first value intotemp, after that no read/writes can be made to thestd::stringstreamand thereforetempis not updated with a new value.A more human readable way of explaining the above; the std::stringstream
sswill think that it has reached the end (which it has, at one point). You’ll need to tell it to "start all over again" (reset all error-flags) for it to be usable in another iteration.How do I solve this issue?
There are a few methods available, to me the most clear (in code readability) is to use a new
std::stringstreamfor each iterator in your loop (see "Example solution #2).Check out the snippets below that all will output:
Example solution #1
Example solution #2
Example solution #3