Answers
The C++ program is given below. The explaination is given as comment within the code itself.
#include <iostream>
#include <string>
#include <stack>
#include <math.h>
using namespace std;
int main() {
string s; //store the number in string format
double n=0; //store the number in decimal formal
int pos=0; //used to convert string to number
stack<int> st; //stack is used to store the whole number in reverse order
cout<<"Enter a decimal number:";
cin>>s;
string::iterator it = s.begin();
//Util we find a .(end of whole number) or the end of the number, push each digit ontostack and count the number of digits.
while(*it!='.' && it!=s.end()){
st.push(*it-48);
it++;
pos=pos+1;
}
//Convert the integral part of the number to n
for(int i=0;i<pos;i++){
n=n+(st.top()*pow(10,i));
st.pop();
}
//consider the fractional part
pos=-1;
if(it!=s.end()){
it++;//needed to shift iterator for .
}
//Convert the fractional part to n
while(it!=s.end()){
n=n+((*it-48)*pow(10,pos));
pos=pos-1;
it++;
}
//Display the decimal number
cout<<n;
}
The screenshot of the output is given below:
NB: Hope it helps. Let me know any concern. Please provide feedback to help you better.
.