我是C++的新手,正在尝试从文本文件中读取值,并将整数仅压入堆栈。我遇到的问题是,当我执行pop()时,从堆栈中出来的值是不同的。
例如,如果我按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.
最佳答案
我能够通过将operandStack.push(content[i]);
更改为operandStack.push(content[i]- '0');
来解决此问题
关于c++ - 压入堆栈的值不是我弹出的C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60715436/