C++ 'stod()' 不工作, 'strtod()' 在编译期间抛出错误

标签 c++

所以我还是 C++ 的新手,我想看看我是否可以使用下面的代码打印基于用户输入的结果。

代码:

/* Input Example */
// Initialization
// Euler's Constant
double eulersConstant = rand();

// Euler's Guess
string eulersGuess;
// Euler's Guess (Double)
double eulersGuessDouble;

// Print
cout << "What is Euler's Constant?";

// Input
getline(cin, eulersGuess);

// Update > Euler's Guess (Double)
eulersGuessDouble = strtod(eulersGuess);

/* Logic
   If
   Euler's Guess (Double) is Euler's Constant.
   > Print
*/
if (eulersGuessDouble == eulersConstant)
   cout << "\tYour guess was right! -- 'Outstanding'" << endl;

else
   cout << "\tYour guess was wrong! -- 'One in a million chance there...'" << endl;

当我在 Windows 命令提示符下使用 g++ 编译它时,我得到这个错误:

Learning C.cpp:116:47: error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*' for argument '1' to 'double strtod(const char*, char**)'
     eulersGuessDouble = strtod(eulersGuess);
                                           ^

当然,所有这些代码都在 int main() 函数中。 我认为问题可能源自 strtod() 函数,但我们将不胜感激,谢谢。

最佳答案

函数strtod接受类似 C 的字符串,也就是 char 数组

double strtod(const char *str, char **endptr);

所以你不能传递类的实例std::string , 但您可能会使用 c_str 获得指向此对象包含的常量字符数组的指针方法。

eulersGuess.c_str();

或者你可以使用函数 std::stod它接受 std::string 参数。

[Live on ideone]

关于C++ 'stod()' 不工作, 'strtod()' 在编译期间抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032881/

相关文章:

c++ - 如何将模板化 vector 传递给 C++ 函数?

java - 在 java 中转换 MFC 桌面应用程序 GUI

c++ - 如果在消息处理程序中使用对象,如何解决内存泄漏问题?

c++ - Xcode 未运行最新版本的 OpenGL,这会导致编译错误

c++ - 为什么 C++ STL 不实现更高效的 std::set 实现?

c++ - 模板模板参数推导与 sfinae

c++ - 从 C++ 的图像流中创建 Qml 视频

基类的c++模板特化

c++ - QtQuick : Change expand icon in TreeView

c++ - LNK2038 : mismatch detected for 'RuntimeLibrary' : value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in file. 对象