我试图找出一种获取用户输入字符并将其转换为双精度的方法。我已经尝试过该atof
功能,但它似乎只能与常量字符一起使用。有没有办法做到这一点?这是我想做的事情的想法:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int main(){
char input;
double result;
cin >> input;
result = atof(input);
}
atof
将字符串(不是单个字符)转换为双精度。如果要转换单个字符,有多种方法:
switch
检查它是哪个字符请注意,C 标准不保证字符代码是 ASCII,因此,第二种方法是不可移植的,因为它适用于大多数机器。
这是一种使用字符串流的方法(顺便说一句,您可能希望将 a 转换std::string
为 a double
,而不是单个char
,因为在后一种情况下会丢失精度):
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string str;
std::stringstream ss;
std::getline(std::cin, str); // read the string
ss << str; // send it to the string stream
double x;
if(ss >> x) // send it to a double, test for correctness
{
std::cout << "success, " << " x = " << x << std::endl;
}
else
{
std::cout << "error converting " << str << std::endl;
}
}
或者,如果您的编译器与 C++11 兼容,则可以使用std::stod函数,该函数将 a 转换std::string
为 a double
,例如
double x = std::stod(str);
后者基本上完成了第一个代码片段的工作,但它会std::invalid_argument
在转换失败的情况下引发异常。
代替
char input
和
char *input