Я новичок в c ++, я пытаюсь прочитать значения из текстового файла и pu sh только целые числа в стек. У меня проблема в том, что когда я делаю pop (), значение, которое выходит из стека, отличается.
Например, если я пу sh a 4, когда я делаю поп, он получается как 52.
Что я делаю неправильно и как я могу это исправить?
IntegerStack. cpp
#include "IntegerStack.h"
#include <cstdlib>
using namespace std;
IntegerStack::IntegerStack()
{
used = 0;
}
void IntegerStack::push(int entry)
{
data[used] = entry;
++used;
}
int IntegerStack::pop()
{
--used;
return data[used];
}
int IntegerStack::peek() const
{
return data[used-1];
}
IntegerStack.h
#ifndef INTEGERSTACK_H
#define INTEGERSTACK_H
#include <cstdlib> // Provides the type size_t.
using namespace std;
class IntegerStack
{
public:
// MEMBER CONSTANT
static const std::size_t CAPACITY = 100;
// DEFAULT CONSTRUCTOR
IntegerStack( ); // Inline
// MODIFICATION MEMBER FUNCTIONS
void push ( int entry );
int pop ( );
// CONSTANT MEMBER FUNCTIONS
std::size_t size ( ) const { return used; } // Inline
bool is_empty ( ) const { return used == 0; } // Inline
int peek ( ) const;
private:
// DATA MEMBERS
int data[CAPACITY];
std::size_t used;
};
#endif // INTEGERSTACK_H
main. cpp
#include <fstream>
#include <iostream>
#include "IntegerStack.h"
using namespace std;
int main()
{
string content;
ifstream inputFile;
cout << "Enter input file name: ";
cin >> content;
IntegerStack operandStack;
// Open file
inputFile.open(content.c_str());
if(inputFile)
{
// Place values in the stack
while(getline(inputFile,content))
{
cout << "Expression: " << content << endl;
for (int i = 0; i < content.size(); i++)
{
if(isdigit(content[i]))
{
cout << "Adding " << content[i] << " to operandStack" << endl;
operandStack.push(content[i]);
int number = operandStack.pop();
cout << "The integer we just pushed: " << number << endl;
}
else
{
// add it to operatorStack
}
}
}
}
// Close file
inputFile.close();
return 0;
}
inix.dat
8 + 4 / 2
( 7 * 4 ) - 2
ВЫХОД
Enter input file name: infix.dat
Expression: 8 + 4 / 2
Adding 8 to operandStack
The integer we just pushed: 56
Adding 4 to operandStack
The integer we just pushed: 52
Adding 2 to operandStack
The integer we just pushed: 50
Expression: ( 7 * 4 ) - 2
Adding 7 to operandStack
The integer we just pushed: 55
Adding 4 to operandStack
The integer we just pushed: 52
Adding 2 to operandStack
The integer we just pushed: 50
Process returned 0 (0x0) execution time : 4.762 s
Press any key to continue.