项目介绍
读取包含若干单词的txt文本文件,并使用堆栈以相反的顺序在屏幕上显示这些单词。
可以假设任何单词的长度都不超过20个字符。
不使用单独的结构或类或STL来实现堆栈。
练习用到txt文件如下所示:
代码实现
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void push(string* string);
string top();
void pop();
bool isEmpty();
const int MAXWORDS = 20;
string words[MAXWORDS];
int index = -1;
int main() {
string a;
ifstream read;
cout << "Enter the filename: " << endl;//display the prompt for the file name
cin >> a;//read in the file name
read.open(a.c_str());//try to open the file
if (!read) {
cout << "Error! Can't find the file" << endl;//print the error message
exit(1);//exit
}
while (!read.eof()) {
for (int index = 0; index<= 20; index++) {
string tool;
read >> tool;
if (tool != "\0")
{
push(&tool);//push in the stack
}
else {
break;//break
}
}
}
read.close();
//while the stack is not empty display the top stack word on the screen followed by pop the top value from the stack
while (isEmpty())//while the stack is not empty
{
cout << top() << endl;//display the top stack
pop();//pop the top
}
return 0;
}
void push(string* string) {
/*If stack is full print "stack full" and exit
inc index
add word to array
*/
if (index > 19) {//If stack is full print "stack full" and exit
cout << "Stack Full" << endl;
exit(1);
}
else {
index++;
words[index] = *string;//add the word to array
}
}
bool isEmpty() {
//if index is -1 return false else return true
if (index == -1)
return false;
else
return true;
}
string top() {
/*
if stack is empty print "stack empty" and exit
return words[index]
*/
if (!isEmpty())//if stack is empty print "stack empty" and exit
{
cout << "Stack empty" << endl;
exit(1);
}
else
{
return words[index];//return words[index]
}
}
void pop() {
//if stack is not empty dec index
if (isEmpty())//stack is not empty
index--;// dec index
}
输出结果如下: