所以我知道如何在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 ++ ? ? ? ?
答案 0 :(得分:2)
看看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;
}
答案 1 :(得分:1)
std::stringstream s(std::string("3.1415927"));
double d;
s >> d;
答案 2 :(得分:1)
这是我的回答here的简化版,用于使用int
转换为std::istringstream
:
std::istringstream i("123.45");
double x ;
i >> x ;
您还可以使用strtod
:
std::cout << std::strtod( "123.45", NULL ) << std::endl ;
答案 3 :(得分:0)
使用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
答案 4 :(得分:0)
string str;
...
float fl;
stringstream strs;
strs<<str;
strs>>fl;
将字符串转换为float。 您可以使用任何数据类型代替float,以便将字符串转换为该数据类型。你甚至可以编写一个将字符串转换为特定数据类型的通用函数。