我是C ++的新手,我的老师给了我一个练习程序来写(这只是为了练习......不是功课,不值得分,所以不要担心)我要做的就是阅读输入从标准输入流中,将它与某些任意字符串进行比较,然后在项目中我必须将其转换为double(因此我无法直接将其作为double读取)。
到目前为止,我可以将其读入并将其存储为字符串string input; cin >> input;
但是,我不知道如何将其转换为double。问题是我只允许使用以下库:
<iostream>, <string>, <cstdlib>, <stdio.h>, and <cassert>.
我查看了atof
中的cstdlib
,但它只包含char *
而不是字符串。有什么建议吗?
答案 0 :(得分:3)
简单:
#include <string>
std::string s = "0.5";
double d = std::stod(s);
答案 1 :(得分:2)
我在cstdlib中查看了atof但它只需要
char *
而不是string
。
在字符串上调用c_str
会为其内容提供char const *
,以便传递给C库函数,这样就可以了
atof(s.c_str()) // where s is an std::string
答案 2 :(得分:2)
试试这个:
#include <sstream>
double a;
const std::string str = "1.0";
std::istringstream is(str);
is >> a;
答案 3 :(得分:0)
C ++字符串类使用C字符数组作为其低级存储。您可以使用此
返回该字符数组