首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在atof中使用substr?

如何在atof中使用substr?
EN

Stack Overflow用户
提问于 2020-07-15 23:00:05
回答 1查看 74关注 0票数 0

.txt文件读取时,我想要转换文件中的一些值,将string转换为doubles。通常,我可以打印所需的值:

代码语言:javascript
复制
string line;
ifstream f; 
f.open("set11.txt");

if(f.is_open()) {

    for(int i = 0; i < 3; i++) {
        
        getline(f, line);
        cout << "Voltage " << i  << ": " << line.substr(0, 9) << endl;
    }
}

f.close();

终端:

代码语言:javascript
复制
Voltage 0: 5.0000000
Voltage 1: 8.0000000
Voltage 2: 1.1000000

但是,当我尝试使它们成为double时,我将命令替换为

代码语言:javascript
复制
cout << "Voltage " << i  << ": " << atof(line.substr(0, 9)) << endl;

我得到了以下错误:

代码语言:javascript
复制
    Voltage 0: Error: atof parameter mismatch param[0] C u C:\Users\User\Desktop\Physics\FTE\Root\set11.c(26)
(class G__CINT_ENDL)9129504
*** Interpreter error recovered ***

这里有什么线索吗?如果我错过了一些明显的东西,很抱歉,我对C++还很陌生

EN

回答 1

Stack Overflow用户

发布于 2020-07-15 23:25:19

问题是,当您传递std::string时,atof()接受const char*作为参数

请改用std::stod

代码语言:javascript
复制
   cout << "Voltage " << i  << ": " << stod(line.substr(0, 9)) << endl;

或者使用.c_str()函数将std::string转换为const char*,然后将其作为参数传递给atof

代码语言:javascript
复制
   cout << "Voltage " << i  << ": " << stod(line.substr(0, 9).c_str()) << endl;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62917856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档