Write a C/C++ program to simulate function atoi. The input should be a string co
ID: 3625188 • Letter: W
Question
Write a C/C++ program to simulate function atoi. The input should be a string contains valid digits (no more than 5 characters). The output should be the converted integer. Loop back to ask for another input until the string "end" is encountered.Bonus (20 points): instead of implementing function atoi, write a program to simulate atof. The input should be a string contains valid digits including a decimal point (no more than 5 characters to the left of the decimal point and no more than 4 digits to the right of the decimal point). The output should be the converted floating-point number. Loop back to ask for another input until the string "end" is encountered.
Explanation / Answer
please rate - thanks
you got the bonus
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
float atof(string);
int main()
{string num;
cout<<"Enter a floating point number: ";
cin>>num;
do
{
cout<<"The number is "<<setprecision(4)<<fixed<<atof(num)<<endl;
cout<<"Enter a floating point number(end to exit): ";
cin>>num;
}while(num.compare("end")!=0);
return 0;
}
float atof(string n)
{float m=(n[0]-'0');
float dec;
int i=1,k=10;
while(n[i]!='.')
m=m*10+(n[i++]-'0');
i++;
dec=(n[i++]-'0')*(1./k);
k*=10;
while(n[i]!='')
{dec=(n[i++]-'0')*(1./k)+dec;
k*=10;
}
return m+dec;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.