简体   繁体   English

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

[英]How to convert user input char to Double C++

I'm trying to figure out a method of taking a user input character and converting it to a double. 我试图找出一种方法来获取用户输入的字符并将其转换为双精度字符。 I've tried the atof function, though it appears that can only be used with constant characters. 我尝试了atof函数,尽管它似乎只能与常量字符一起使用。 Is there a way to do this at all? 有没有办法做到这一点? Heres an idea of what I'd like to do: 以下是我想做什么的想法:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

int main(){

    char input;
    double result;

    cin >> input; 

    result = atof(input);
}

atof converts a string (not a single character) to double. atof字符串 (不是单个字符)转换为双精度。 If you want to convert a single character, there are various ways: 如果要转换单个字符,则有多种方法:

  • Create a string by appending a null character and convert it to double 通过添加空字符创建字符串并将其转换为double
  • Subtract 48(the ASCII value of '0') from the character 从字符中减去48(ASCII值“ 0”)
  • Use switch to check which character it is 使用switch检查它是哪个字符

Note that the C standard does not guarantee the character codes are in ASCII, therefore, the second method is unportable, through it works on most machines. 请注意,C标准不保证字符代码为ASCII,因此,第二种方法不可移植,因为它适用于大多数计算机。

Here is a way of doing it using string streams (btw, you probably want to convert a std::string to a double , not a single char , since you lose precision in the latter case): 这是使用字符串流进行操作的一种方法(顺便说一句,您可能希望将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;
    }
}

Or, if your compiler is C++11 compliant, you can use the std::stod function, that converts a std::string into a double , like 或者,如果您的编译器符合C ++ 11,则可以使用std :: stod函数,该函数会将std::string转换为double ,例如

double x = std::stod(str);

The latter does basically what the first code snippet does, but it throws an std::invalid_argument exception in case it fails the conversion. 后者基本上可以执行第一个代码段的操作,但是如果转换失败,则会抛出std::invalid_argument异常。

Replace 更换

char input

with

char *input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM