C++ error converting a string to a double

一笑奈何 提交于 2019-12-11 12:22:23

问题


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?


回答1:


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



回答2:


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;



回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/1694798/c-error-converting-a-string-to-a-double

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!