Search code examples
c++atof

C++ error converting a string to a double


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?


Solution

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