如何将用户输入的字符转换为Double C++
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
将字符串(不是单个字符)转换为双字符。如果你想转换单个字符,有多种方法:
- 通过附加一个null字符创建字符串,并将其转换为双字符
- 从字符中减去48(ASCII值"0")
- 使用
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
相关文章:
- C++在数学计算中将double转换为int
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- 错误:无法将"<lambda(double)>"转换为"double(*)(double)"
- 如何正确将"strings"转换为"double"?
- Zedboard zynq-7000 Opencl 浮点数从类型 'double*' 强制转换为类型 'double' 无效
- "std::function<double(double)>"到"double (*)(double)"之间的转换
- C++ 模板函数无法将"std:string"转换为"double"作为回报
- 缩小从double到float的转换
- 在不复制数据的情况下,将double数组转换为只有double成员的structs数组
- 将 mwArray 转换为 std::vector<double>
- 使用词法强制转换在'string to double'中设置双精度变量的精度
- 如何将 Java double[][] 转换为 C++ <vector<vector>> JNI?
- 从 std::vector<double> 到 Python 列表的转换失败(提升 python)
- 转换 cv::mat 转换为 std::矢量<double>并发症
- 将双数组转换为标准::复杂<double>
- 将 std::vector<boost::optional<double>> 转换为 std::vector<double>
- 将 double* 转换为 std::vector<double> (C++)
- 无法将复数<double>转换为双精度
- 将 int 转换为双精度以执行 std::complex <double>的"*"操作
- "double(*)(string, double, double)"尝试传递函数C++时"double"转换错误