将输入字符串转换为float / double C ++ [英] Converting Input string to float/double C++

查看:103
本文介绍了将输入字符串转换为float / double C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道如何在C#中做到这一点,但不懂C ++。我正在尝试将给定用户的输入解析为双精度型(稍后再做数学运算),但是我对C ++不熟悉,遇到了麻烦。

So I know how to do it in C#, but not C++. I am trying to parse giver user input into a double (to do math with later), but I am new to C++ and am having trouble. Help?

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++ ? ? ? ?

推荐答案

看看atof。请注意,atof使用cstrings,而不是字符串类。

Take a look at atof. Note that atof takes cstrings, not the string class.

#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/

这篇关于将输入字符串转换为float / double C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆