저는 C++을 처음 사용 했으므로 문자열 변수를 숫자로 변환하는 데 도움이 필요합니다. 나는 그 사람의 나이와 그녀의 내년 나이를 화면에 인쇄해야하지만 어떻게되는지 알아 내지 못합니다. 문자열을 사용하여 수학을 할 수 없습니다. 그럼 제발 몇 가지 예를 쏴주세요.C++에서 atof()를 사용하여 문자열을 부동으로 변환
//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());
}
어디에서 값을 가져 옵니까? –
'std :: stof'를 사용하십시오. 그것은 에러 검사를 가지며 불필요한'c_str()'호출을 요구하지 않는다. – chris
이 변수가 어떻게 선언되는지, 값이 어디서 오는가? – WhozCraig