如何将用户输入的字符转换为 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);
}

atofstring(不是单个字符)转换为 double。如果要转换单个字符,有多种方式:

  • 通过附加空字符创建字符串并将其转换为双精度
  • 从字符中减去 48('0' 的 ASCII 值)
  • 使用switch查看是哪个字符

注意C标准不保证字符编码为ASCII,因此,第二种方法不可移植,但它适用于大多数机器。

替换

char input

char *input

这是一种使用字符串流的方法(顺便说一句,您可能希望将 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 异常以防转换失败。