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.
Use the STL stack
1). ANSWER :
GIVENTHAT :
C++ CODE :-
#include<bits/stdc++.h>
using namespace std;
int main(){
string str; cin>>str; // get the no in string format
int n = str.size();
bool isdecimal = false;
for(int i = 0; i < n; i++) // check if is decimal or not
if(str[i] == '.')
isdecimal = true;
double no = 0;
if(isdecimal){ // if the no if decimal
stack<int> stk;
double f = 0;
for(int i = 0 ; i < n; i++) // push all letter of string into
stack
stk.push(str[i]);
while(!stk.empty()){ // this will make the fractional part
char c = stk.top(); // pop top
stk.pop();
if(c =='.') break; // if decimal if found stop
f = f + (c-'0'); // add the top and divide it by 10
f /= 10;
}
int t = 0;
while(!stk.empty()){ // this will make the non fractional part of
the no
char c = stk.top();
stk.pop();
no = (c-'0')*pow(10,t)+no;
t++;
}
no = no+f; // add fractional and non fractional part to get the
no
}
else
for(int i = 0; i < n; i++) // if the no is not fractional
no = no*10 + (str[i]-'0');
cout<<no;
}
Sample Run :