【问题标题】:Converting Input string to float/double C++将输入字符串转换为浮点/双精度 C++
【发布时间】:2013-05-30 17:38:32
【问题描述】:

所以我知道如何在 C# 中做到这一点,但不是 C++。我正在尝试将给予者用户输入解析为双精度(稍后进行数学运算),但我是 C++ 新手并且遇到了麻烦。帮忙?

C#

 public static class parse
        {
            public static double StringToInt(string s)
            {
                double line = 0;
                while (!double.TryParse(s, out line))
                {
                    Console.WriteLine("Invalid input.");
                    Console.WriteLine("[The value you entered was not a number!]");
                    s = Console.ReadLine();
                }
                double x = Convert.ToDouble(s);
                return x;
            }
        }

C++ ? ? ? ?

【问题讨论】:

标签: c++ string double


【解决方案1】:

看看atof。注意 atof 需要 cstrings,而不是 string 类。

#include <iostream>
#include <stdlib.h> // atof

using namespace std;

int main() {
    string input;
    cout << "enter number: ";
    cin >> input;
    double result;
    result = atof(input.c_str());
    cout << "You entered " << result << endl;
    return 0;
}

http://www.cplusplus.com/reference/cstdlib/atof/

【讨论】:

    【解决方案2】:
    std::stringstream s(std::string("3.1415927"));
    double d;
    s >> d;
    

    【讨论】:

      【解决方案3】:

      这是我的答案here 的简化版本,用于使用std::istringstream 转换为int

      std::istringstream i("123.45");
      double x ;
      i >> x ;
      

      你也可以使用strtod:

      std::cout << std::strtod( "123.45", NULL ) << std::endl ;
      

      【讨论】:

        【解决方案4】:

        使用atof

        #include<cstdlib>
        #include<iostream>
        
        using namespace std;
        
        int main() {
            string foo("123.2");
            double num = 0;
        
            num = atof(foo.c_str());
            cout << num;
        
            return 0;
        }
        

        输出:

        123.2
        

        【讨论】:

          【解决方案5】:
          string str;
          ...
          float fl;
          stringstream strs;
          strs<<str;
          strs>>fl;
          

          这会将字符串转换为浮点数。 您可以使用任何数据类型代替浮点数,以便将字符串转换为该数据类型。你甚至可以编写一个将字符串转换为特定数据类型的通用函数。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-10-10
            • 2015-04-10
            • 1970-01-01
            • 2020-06-16
            • 1970-01-01
            • 2014-01-01
            相关资源
            最近更新 更多