开发者

how to convert string value into double format in c++

How do I convert a s开发者_StackOverflow中文版tring value into double format in C++?


If you're using the boost libraries, lexical cast is a very slick way of going about it.


Use stringstream :

#include <sstream>

stringstream ss;
ss << "12.34";
double d = 0.0;
ss >> d;


You can do with stringstream. You can also catch invalid inputs like giving non-digits and asking it to convert to int.

#include <iostream> 
#include <sstream>
using namespace std;

int main()
{
    stringstream s;
    string input;
    cout<<"Enter number: "<<endl;
    cin>>input;
    s.str(input);
    int i;
    if(s>>i)
        cout<<i<<endl;
    else
        cout<<"Invalid input: Couldn't convert to Int"<<endl;
}

If conversion fails, s>>i returns zero, hence it prints invalid input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜