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

时间:2012-01-23 03:30:19

标签: c++

我在将字符串转换为double时遇到问题。 我的字符串已使用“string”函数声明,因此我的字符串是:

string marks = "";

现在将它转换为双重我在互联网上找到的地方使用word.c_str(),所以我做了。我打电话给它并像这样使用它:

doubleMARK = strtod( marks.c_str() );

这类似于我在网上找到的例子:

n1=strtod( t1.c_str() );

显然,这就是它的完成方式。但是,当然,它不起作用。我需要另一个参数。我相信一个指针?但是我在这一点上已经失去了我想要做的事情。它需要一个存储价值的地方吗?或者是什么?

我还需要将这个字符串转换成一个整数,我还没有开始研究如何做,但是一旦我发现并且我有错误,我会编辑它并在这里发布。

2 个答案:

答案 0 :(得分:9)

您是否有理由不使用std::stodstd::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:

  

如果[第二个参数]不是空指针,该函数还会将endptr指向的值设置为指向数字后面的第一个字符。

并且不需要非NULL

答案 1 :(得分:0)

回到C的Bad Old Dark Days,我会做一些像这样丑陋和不安全的事情:

char sfloat[] = "1.0";
float x;
sscanf (sfloat, "%lf", &x);

在C ++中,您可能会这样做:

// REFERENCE: http://www.codeguru.com/forum/showthread.php?t=231054
include <string>
#include <sstream>
#include <iostream>

template <class T>
bool from_string(T& t, 
                 const std::string& s, 
                 std::ios_base& (*f)(std::ios_base&))
{
  std::istringstream iss(s);
  return !(iss >> f >> t).fail();
}

int main()
{
  int i;
  float f;

  // the third parameter of from_string() should be 
  // one of std::hex, std::dec or std::oct
  if(from_string<int>(i, std::string("ff"), std::hex))
  {
    std::cout << i << std::endl;
  }
  else
  {
    std::cout << "from_string failed" << std::endl;
  }

  if(from_string<float>(f, std::string("123.456"), std::dec))
  {
    std::cout << f << std::endl;
  }
  else
  {
    std::cout << "from_string failed" << std::endl;
  }
  return 0;
} 

但就个人而言,我建议这样做:

  

http://bytes.com/topic/c/answers/137731-convert-string-float

     

有两种方法。 C为你提供了一个在char之间转换的strtod   数组和双:

// C-ish: 
input2 = strtod(input.c_str(), NULL);
  

C ++流提供了各种各样的转换   类型。将字符串与流一起使用的方法是使用字符串流:

// C++ streams: 
double input2;
istringstream in(input); 
input >> input2;