算法和数据结构项目练习1-堆栈

Implementing a Stack

项目介绍

读取包含若干单词的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
}

输出结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值