tags:

views:

392

answers:

4

I am trying to convert a string to a double. The code is very simple.

            double first, second;
            first=atof(str_quan.c_str());
            second=atof(extra[i+1].c_str());
            cout<<first<<" "<<second<<endl;
            quantity=first/second;

when trying to convert extra, the compiler throws this gem of wisdom at me:

error: request for member c_str in extra.std::basic_string<_CharT, _Traits, _Alloc>::operator[] with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator(i + 1))), which is of non-class type char

I have no idea what that means. if I cout extra[i+1], I get 3. If I leave extra as a string, the program tries to div first (2) by 51 (ascii for 3). What the heck is going on?

+6  A: 

It sounds like extra is a std::string, so extra[i+1] returns a char, which is of non-class type.

It sounds like you are trying to parse the string extra starting from the i+1th position. You can do this using:

second = atof(extra.substr(i + 1).c_str());
James McNellis
This worked perfectly! Thank you. I have been at this for over an hour.
piratebill
Alternativly: `extra.c_str()+(i+1)` which avoids creating a temporary string object
sellibitze
+1  A: 

Based on the error message, extra is of type std::string. When you do extra[i+1], the result is of type char and contains the character in the string extraat position i+1.

Probably not what you intended.

As a fix, replace extra[i+1] with a new string, as follows:

extra2 = extra.substr(i+1);
// ...
second=atof(extra2.c_str());

A better way to handle this conversion (which is less prone to error) is to use stringstreams:

stringstream ss(str_quan);
double first;
ss >> first;
greyfade
A: 

When asking for help it is often reallyt usfull to provide a compilable example.

My guess (and I emphasis guess becuase there is not enough type information or line numbers).

second=atof(extra[i+1].c_str());

// Guess 
// extra is std::string.

Thus extra[x] is returning a char which does not have a method c_str()

Martin York
+1  A: 

You haven't said, but I think "extra" is of type std::string. So the expression "extra[i+1] is character "i+1" of "extra", which seems to be '3'.

What are you actually trying to do?

If you just want characters i+1 through to the end of "extra" (and you know how long extra is), you want something like:

 second = atof(extra.c_str() + i + 1);
janm
It is preferable to use `substr` for this purpose since it will throw `std::out_of_range` if `i + 1` is past the end of the string.
James McNellis
At the cost of a temporary; that's why I said "and you know how long extra is". However, I take your point; an alternative would be "assert(i + 1 < extra.size())" before the call to atof(). As we make this code more idiomatic C++, we'd ditch atof(), and possibly use boost::iterator_range and boost::lexical_cast ...
janm