【问题标题】:How to use substr with atof?如何将 substr 与 atof 一起使用?
【发布时间】:2020-11-05 03:04:33
【问题描述】:

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

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();

终端:

Voltage 0: 5.0000000
Voltage 1: 8.0000000
Voltage 2: 1.1000000

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

cout << "Voltage " << i  << ": " << atof(line.substr(0, 9)) << endl;

我收到以下错误:

    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++ 还是很陌生

【问题讨论】:

  • line.substr(0, 9).c_str()?std::atof 的文档中所述,它接受const char*,而std::string 则不是。
  • std::stof?包括更好的验证并允许更好的错误处理。
  • "set11.c" 是 C++ 源文件的一个非常奇怪的名称。
  • std::stod 如果需要双打。
  • @AlgirdasPreidžius 非常感谢!

标签: c++ string double root atof


【解决方案1】:

问题是atof()const char* 作为参数,而您正在传递std::string

改用std::stod

   cout << "Voltage " << i  << ": " << stod(line.substr(0, 9)) << endl;

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

   cout << "Voltage " << i  << ": " << stod(line.substr(0, 9).c_str()) << endl;

【讨论】:

  • 如果stod 可以采用string_view 这将是简单而伟大的。唉...
猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2023-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
相关资源
最近更新 更多