我是 C++ 新手,需要帮助将我的字符串变量转换为数字。我需要在屏幕上打印这个人的年龄和她明年的年龄,但我不知道怎么做。我不能用字符串来做数学。那么你能给我举几个例子吗?
我试着这样做:
//converts F to C
ctemp=(ftemp-32)*5.0/9.0;
//calculates age
age2 = age + 1 ; age2 = atof (age2.c_str()); age = atof (age.c_str());
cout<<name<<" is "<<age<<" now, and will be " <<age2<<" a year from now.\n"<<"Its "<<ftemp<<" in "<<city<<"--- That's "<<setprecision(2)<<ctemp<<" degrees C"<<endl;
编辑:
int main() {
int city;
double ftemp, ctemp,age,age2;
string buf,name; //Ask user to enter age, name, temperature and city
cout<<"Enter your age\n";
cin>>buf;
age = atof(buf.c_str());
cout<<"Enter your full name please\n";
getline(cin,name);
cout<<"Enter the outside temperature please\n";
cin>>buf;
ftemp=atof(buf.c_str());
cout<<"Enter the current city you are in\n";
cin>>buf;
city=atoi(buf.c_str());
}