我在将字符串转换为 double 时遇到问题。 我的字符串已使用“字符串”函数声明,所以我的字符串是:
string marks = "";
现在要将其转换为 double ,我在互联网上的某个地方找到了可以使用 word.c_str() 的方法,所以我这样做了。我这样调用它并使用它:
doubleMARK = strtod( marks.c_str() );
这类似于我在网上找到的例子:
n1=strtod( t1.c_str() );
显然,这就是它的完成方式。但当然,这是行不通的。我需要另一个参数。我相信一个指针?但是此时我不知道我应该做什么。它是否需要一个地方来存储值(value)或其他东西?或者是什么?
我还需要将这个字符串转换成一个整数,我还没有开始研究如何做,但是一旦我发现并且如果我有错误,我会编辑它并将它们发布在这里。
最佳答案
您有没有使用 std::stod
的原因?和 std::stoi
?它们至少比脆弱的 strtod
强大 9 个级别。
Example
#include <iostream>
#include <string>
int main() {
using namespace std;
string s = "-1";
double d = stod(s);
int i = stoi(s);
cout << s << " " << d << " " << i << endl;
}
输出
-1 -1 -1
如果您必须使用strtod
,那么只需将NULL
作为第二个参数传递即可。根据 cplusplus.com:
If [the second parameter] is not a null pointer, the function also sets the value pointed by endptr to point to the first character after the number.
并且不需要非NULL
。
关于c++ - 将字符串转换为 double 和 int。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8966903/