c++ - 将字符串转换为 double 和 int。如何?

标签 c++

我在将字符串转换为 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/

相关文章:

c++ - QT4 qlistview保存手动移动的图标位置,下次使用

c++ - 错误 LNK2019 : unresolved external symbol _luaJIT_setmode

c++ - 无法减少代码(cout与exit结合)

c++ - 求二叉搜索树的中位数,C++

c++ - For循环与使用相对较旧的编译器的标准库算法

c++ - Qt QList C3892 : cannot assign to a variable that is const

c++ - 如何从任何容器中取出?

c++ - 在Intel x86中读取缓存行与部分缓存行

c++ - 带 if 条件的作用域锁

c++ - 在 hashmap/unordered_map 中,当 value 已经包含 key 时,是否可以避免数据重复