[英]How to convert user input char to Double C++
我试图找出一种方法来获取用户输入的字符并将其转换为双精度字符。 我尝试了atof
函数,尽管它似乎只能与常量字符一起使用。 有没有办法做到这一点? 以下是我想做什么的想法:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int main(){
char input;
double result;
cin >> input;
result = atof(input);
}
atof
将字符串 (不是单个字符)转换为双精度。 如果要转换单个字符,则有多种方法:
switch
检查它是哪个字符 请注意,C标准不保证字符代码为ASCII,因此,第二种方法不可移植,因为它适用于大多数计算机。
这是使用字符串流进行操作的一种方法(顺便说一句,您可能希望将std::string
转换为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函数,该函数会将std::string
转换为double
,例如
double x = std::stod(str);
后者基本上可以执行第一个代码段的操作,但是如果转换失败,则会抛出std::invalid_argument
异常。
更换
char input
同
char *input
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.