如何在不使用 atof 函数的情况下将命令行添加为数字数据

How do I add command lines as numeric data without using the atof function?

本文关键字:命令行 情况下 添加 数据 数字 函数 atof      更新时间:2023-10-16

有没有办法避免使用 atof 函数?如何将字符串转换为浮点数?

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
    double x = 0;
    for(int i=0; i<argc; i++)
    x += atof(argv[i]);
    cout<<x<<endl;
    return 0;
}

您可以使用stringstream .

#include <iostream>
#include <sstream>
using namespace std;
int main () {    
  int val;
  stringstream ss (stringstream::in | stringstream::out);
  ss << "120";   
  ss >> val;    
  return 0;
}
为了在

C++中将字符串转换为浮点数,现在(自 C++11 的标准化以来)建议使用 std::stofstd::stodstd::strold 之一(这些函数已添加到C++标准库中):

std::string s = "120.0";
float f = std::stof(s);
double d = std::stod(s);
long double ld = std::stold(s);

与 C 标准库中的功能相比,首选这些功能的主要原因是安全性:

  1. 它们不是在原始指针上操作,而是在字符串对象上操作(这也导致便利性和可读性的微小改进:在使用std::string时不必一遍又一遍地调用c_str());

  2. 当无法转换时,它们不会表现出未定义的行为(它们可以预见地抛出有据可查的异常)。

您可以使用

boost::lexical_cast在书面类型和数字类型之间进行转换,这种方式对C++来说非常习惯。

#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
using namespace std;
int main(int argc, char* argv[])
{
    double x = 0;
    for(int i=1; i<argc; i++)
    x += boost::lexical_cast<float>(argv[i]);
    cout<<x<<endl;
    return 0;
}