C++ istringstream in loop not changing its value
I'm fairly new to c++ and have encountered a problem where by searching alone I couldn't find a solution.
The problem is, why does the istringstream never changes its value inside the loop below?
It takes the value from dirs[ 0 ] and dirs[ 1 ] and never changes them to the increasing int i. Btw. the values in dirs[ i ] and dirs [ i + 1 ] are stored as hex values (e.g. 0F9C8924).
Below is my latest setup, i've tried several other ways but with no success, for example having istringstream inside the loop and with ios_base::trunc and whatsoever.
Also dirs[ i ]
etc. DO have different values and are read correctly, but when trying to make the string hex into a unsigned int via istringstream it never takes the new values.
unsigned int f;
unsigned int t;
istringstream ss;
istringstream ss2;
for( int i = 0; i < count; i+=3 ) {
ss.clear();
ss2.clear();
ss.str( dirs[ i ] );
ss2.str( dirs[ i + 1 ] );
ss >> f;
ss2 >> t;
// do something else with dirs[ i + 3 ], not relevant
}
count
and dirs
are a global variable and count
is increased in another function, its the count of values in dirs
.
I am sorry if this has been a开发者_JS百科sked before, but the solutions I found somehow didn't work for me.
Such as ss.clear()
or while( ss >> f )
Thanks in advance for any help provided.
The question is a bit confusing. Do you mean that the input is a string like "0F9C8924"?
If so, try ss >> hex >> f;
.
You should write some error handling into your code so that you know when and why things are going wrong. ss.clear()
just blindly clears error flags without ever finding out why they were set in the first place.
Try this:
unsigned int f;
unsigned int t;
for( int i = 0; i < count; i+=3 )
{
istringstream ss1( dirs[ i ] );
istringstream ss2( dirs[ i + 1 ] );
ss1 >> f;
ss2 >> t;
// do something else with dirs[ i + 3 ], not relevant
}
I assume you thought clear() would empty the stream. And str(<string>) would set some text into the stream. Probably best to declare the stringstream inside the loop. This means they are destroyed at the end of the loop and re-created each time the loop is entered. Then you can just initialize them with there constructor.
This prints out the decimal values of the hex strings. Is this what you want?
#include <sstream>
#include <iostream>
using std::istringstream;
unsigned int f;
unsigned int t;
const char * dirs[12] = {
"0x15", "0x16", "dummy",
"0x11", "0x12", "dummy",
"0x115", "0x116", "dummy",
"0x111", "0x112", "dummy"
};
unsigned int count = sizeof(dirs) / sizeof(const char *);
int main(int, char **) {
for( unsigned int i = 0; i < count; i+=3 )
{
istringstream ss1( dirs[ i ] );
istringstream ss2( dirs[ i + 1 ] );
ss1 >> std::hex >> f;
ss2 >> std::hex >> t;
std::cout << "f is " << f << std::endl;
std::cout << "t is " << t << std::endl;
// do something else with dirs[ i + 2 ], not relevant
}
std::cin.get();
return 0;
}
精彩评论