char to const char* with atof
Hello, I have this problem; it gets a runtime error. Why?
Code:
vector<double> vec;
string s =" 123213131313131331";
string::iterator it_s = s.begin();
for ( ; it_s != s.end(); ++it_s) {
vec.push_back( (double) atof( (const char *) (*it_s) ) ); //runtime error
}
Re: char to const char* with atof
You can't cast a char to const char * like that... atof() expects adress of a C string and outputs a float. What are you trying to achieve?
Re: char to const char* with atof
I edited it. maybe more clear now (convert each digit to double and psuh into vector)
Re: char to const char* with atof
Khem.... Lot to learn you still have, young one :)
Code:
QVector<double> vec;
std::string str;
for(int i=0;i<str.length();i++){
int val = str[i] - '0';
if(val<0 || val>9) continue;
vec.push_back((double)val);
}
Re: char to const char* with atof
thanks but isn't there a way to use that iterator on the string, please?
EDIT: and why a cast at C style ( "(double)" I mean )
Re: char to const char* with atof
Use an iterator if you want - I don't mind. The heart of the solution is the conversion of a character to digit, not the way you traverse the string. The cast is "just in case" so that I'm more confident it compiles.