如何在不使用 atof 函数的情况下将命令行添加为数字数据
How do I add command lines as numeric data without using the atof function?
有没有办法避免使用 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::stof
、 std::stod
和 std::strold
之一(这些函数已添加到C++标准库中):
std::string s = "120.0";
float f = std::stof(s);
double d = std::stod(s);
long double ld = std::stold(s);
与 C 标准库中的功能相比,首选这些功能的主要原因是安全性:
它们不是在原始指针上操作,而是在字符串对象上操作(这也导致便利性和可读性的微小改进:在使用
std::string
时不必一遍又一遍地调用c_str()
);当无法转换时,它们不会表现出未定义的行为(它们可以预见地抛出有据可查的异常)。
您可以使用
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;
}
相关文章:
- 如何在不传递命令行参数的情况下在 c++ 中设置环境变量
- 在不传输的情况下更改 Win32 中的串行端口波特率
- 在Slurm和使用命令的情况下,MPI结果不同
- 如何在不使用文件扩展名的情况下使用命令行参数打开C++中的文本文件?
- 串行读取()不会在没有数据接收的情况下返回值
- 如何在没有缓冲的情况下使用 parquet-cpp 写入面向流/行的数据?
- C++:如何在不将命令传递给 shell 的情况下执行文件?
- 程序在没有操作系统信号的情况下在函数中的特定行挂起
- 句子转换器在存在新行的情况下不起作用
- 如何在不破坏单词的情况下将字符串拆分为行
- 特征在不复制的情况下对行重新排序
- 我如何在不使用扩展名的情况下给出命令行参数,而不是./a.out 3 4,而是./a 3 4
- 如何在不更改命令行的情况下禁用断言
- C++ - 在没有物理设备的情况下测试串行端口
- 如何在不添加换行符的情况下将文本附加到QPlainTextEdit,并保持滚动在底部
- C++在不使用字符串流的情况下读取具有任意长度和格式的行的多行文件
- 如何创建一个可以在GUI对话模式下或通过命令行启动的C MFC程序
- 如何在不使用 atof 函数的情况下将命令行添加为数字数据
- 是否可以在不显示窗口的情况下启动命令行应用程序
- 如何在没有IO窗口(命令行窗口)的情况下运行exe