簡體   English   中英

將輸入字符串轉換為float / double C ++

[英]Converting Input string to float/double C++

所以我知道如何在C#中實現它,而不是C ++。 我試圖將giver用戶輸入解析為double(稍后再做數學運算),但我是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 ++?

看看atof。 請注意,atof需要cstrings,而不是字符串類。

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

std::stringstream s(std::string("3.1415927"));
double d;
s >> d;

這是我回答的簡化版本, 在這里它是為轉換為int使用std::istringstream

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

你也可以使用strtod

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

使用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
string str;
...
float fl;
stringstream strs;
strs<<str;
strs>>fl;

這會將字符串轉換為float。 您可以使用任何數據類型代替float,以便將字符串轉換為該數據類型。 你甚至可以編寫一個將字符串轉換為特定數據類型的泛型函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM