C++ error converting a string to a double

6.9k Views Asked by At

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](((unsigned int)(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?

4

There are 4 best solutions below

2
On BEST ANSWER

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());
0
On

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;
0
On

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()

2
On

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);