In: Computer Science
This is 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. I keep getting an error around line 31 stating that there is an undefined function stObj.push(*it - 48); -- any help to fix my error would be helpful, thank you in advance.
Here is my code:
#include <iostream>
#include <string>
#include <stack>
#include <math.h>
using namespace std;
//main method
int main()
{
//Declare local variables
string input;
double number = 0;
int index = 0;
//declare the stack of type integer
stack<int> stObj;
//prompt and read the input number
//of type string
cout << "Enter a decimal number:";
cin >> input;
//declare iterator
string::iterator iterObj = input.begin();
//push the number into the stack
//increment the index of the stack
while (*iterObj != '.' && iterObj !=
input.end())
{
//push into the stack
stObj.push(*it - 48);
iterObj++;
index = index + 1;
}
//compute the integral part of the number
for (int i = 0; i < index; i++)
{
number = number +
(stObj.top()*pow(10, i));
stObj.pop();
}
//consider the fractional part
index = -1;
if (iterObj != input.end())
{
//increment the interator for the
memory address
iterObj++;
}
//compute the fractional part to number
while (iterObj != input.end())
{
number = number + ((*iterObj -
48)*pow(10, index));
index = index - 1;
iterObj++;
}
//Display the decimal number
cout << "The numeric format: " << number
<< endl;
}
Correct C++ Code:
#include <iostream>
#include <string>
#include <stack>
#include <math.h>
using namespace std;
//main method
int main()
{
//Declare local variables
string input;
double number = 0;
int index = 0;
//declare the stack of type integer
stack<int> stObj;
//prompt and read the input number
//of type string
cout << "Enter a decimal number:";
cin >> input;
//declare iterator
string::iterator iterObj = input.begin();
//push the number into the stack
//increment the index of the stack
while (*iterObj != '.' && iterObj != input.end())
{
//push into the stack
stObj.push(*iterObj - 48);
iterObj++;
index = index + 1;
}
//compute the integral part of the number
for (int i = 0; i < index; i++)
{
number = number + (stObj.top()*pow(10, i));
stObj.pop();
}
//consider the fractional part
index = -1;
if (iterObj != input.end())
{
//increment the interator for the memory address
iterObj++;
}
//compute the fractional part to number
while (iterObj != input.end())
{
number = number + ((*iterObj - 48)*pow(10, index));
index = index - 1;
iterObj++;
}
//Display the decimal number
cout << "The numeric format: " << number <<
endl;
}
Bold change has to be made in your code.
*it is not defined.
It should be changed to *iterObj.
Output:
