我是 C++ 的新手,我正在尝试编写代码将字符串转换为 float (我不应该使用 atof),但我的代码输出是 0 。请帮助我了解问题所在:
char A[10];
int N[10],c,b=10,a=0,p=0,i;
float s=0.1;
cout<<"reshte ra vared namaeed:";
cin>>A;
for( i=0;A[i]=!'.';i++)
{
a=(a*b)+(A[i]-48);
}
for(A[i]=='.';A[i]!='\0';i++)
{
p=(p*s)+(A[i]-48);
}
cout<<a+p;
getch();
return 0;
最佳答案
您可以使用 StringStream。
#include <iostream>
#include <string>
#include <sstream>
你可以很容易地使用它。例如:
stringstream sstr;
string s;
float f;
cin >> s; // Get input from stdin
sstr << s; // Copy string into stringstream
sstr >> f; // Copy content of stringstream into float
cout << f << endl; // Output your float
当然你可以把它放到一个函数/模板中。
关于c++ - 坚持我的 C++ 作业(将字符串转换为 float ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22402781/