如何将用户输入的字符转换为Double C++

How to convert user input char to Double C++

本文关键字:转换 Double C++ 字符 用户 输入      更新时间:2023-10-16

我正试图找到一种方法,将用户输入的字符转换为双精度字符。我尝试过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