我在使用 Qt Creator(4.10) 作为 IDE / gcc 7.4.0 的 Ubuntu 18.0.4 中使用 std::atof 遇到了这种奇怪的行为:
当我从 QtCreator 以调试模式运行时,它会正常解析字符串。但是当我正常运行时它会落地。
具有此行为的示例代码:
std::string exampleStr = "3.0303";
std::cout << "string value: " << exampleStr << std::endl;
std::cout << "double value - c_str(): " << std::atof(exampleStr.c_str()) << std::endl;
从 IDE 正常运行的输出:
字符串值:3.0303
双值 - c_str(): 3
直接从可执行文件运行的输出:
字符串值:3.0303
双值 - c_str(): 3
带调试模式的输出:
字符串值:3.0303
双值 - c_str(): 3.0303
我已经尝试过 std::stof 和 std::strtof。两者一样。有人知道这个错误的原因或解决方法吗?
编辑: 我已经解决了这个问题,但仍然想知道这种行为的原因。
std::string exampleStr = "3.0303";
std::stringstream ss;
ss << exampleStr;
float val = 0;
ss >> val;
std::cout << "Float value: " << val << std::endl;