【发布时间】:2019-01-07 07:24:34
【问题描述】:
我必须一次读取每个单词的文本文件,然后将该单词推送到堆栈,然后一次弹出每个单词以在显示器中打印。我尝试了以下代码,但运行程序后,编译器只显示空白屏幕而没有错误。 笔记: 我不允许使用类或结构或使用 STL 来实现堆栈。堆栈必须使用固定大小的单词数组和用于指示堆栈顶部的索引整数来实现
我的文本文件是这样的:
one two three four five
six seven and so on
输出应该是:
no os dna neves xis ...
main.cpp
using namespace std;
char word;
void push(char);
void pop();
void displaywords();
int count = 0;
const int arr_Size=50;
string stack[arr_Size];
int main()
{
//string word;
ifstream infile;
infile.open("data.txt");
if(!infile)
{
cerr << "An error occurred while opening the file.";
exit(1);
}
do
{
cin >> word;
if (infile.fail())
break;
cout << word;
push(word);
}while(infile.eof());
infile.close();
while(stack!=NULL) // trying to write code for stack is not null
{
displaywords();
pop();
}
return 0;
}
void push(char word)
{
count = count + 1;
stack[count] = word;
}
void displaywords()
{
cout << "PUSHED " << " " << stack[count] << " ." << endl;
}
void pop()
{
count = count - 1;
}
【问题讨论】:
-
还有
std::stack。无需自己动手。
标签: c++ stack file-handling