In: Computer Science
In c++, write a program that reads a string consisting of a positive integer or a positive decimal number and converts the number to the numeric format. If the string consists of a decimal number, the program must use a stack to convert the decimal number to the numeric format.
#include<iostream>
#include <string>
#include<queue>
#include<cmath>
using namespace std;
int main()
{
string number;
queue <char> st;
cout<<"enter a number:\t";
getline(cin, number);
size_t found = number.find(".");
if (found != string::npos)
{
double dnum = 0;
int j = 0;
while(number[j] != '\0')
{
st.push(number[j]);
j++;
}
int flag = 0,count = 0;
while(!st.empty())
{
if(st.front() ==
'.')
{
st.pop();
flag = 1;
continue;
}
if(flag ==
1)
{
count++;
int k = int(st.front()) - 48;
dnum = dnum + k * (pow(0.1, count));
st.pop();
}
else
{
int k = int(st.front()) - 48;
dnum = dnum * 10 + k;
st.pop();
}
}
cout<<dnum<<endl;
}
else
{
int num = 0;
int i = 0;
while(number[i] != '\0')
{
num = num * 10 +
(int(number[i]) - 48);
i++;
}
cout<<"number
is:\t"<<num<<"\n";
}
}
If you have any doubts please comment and please don't dislike.