您好,我是 C++ 的新手,我无法理解如何将文本文件中的元素推送和弹出到数组并以相反的顺序显示这些元素,例如,如果我有一个名为 hero.txt 的文本文件元素 Goku Luffy Naruto 我希望输出是 Naruto Luffy Goku 这是我目前所拥有的
string hero[100]; // array to store elements
int count=0;
int main()
{
fstream myfile;
string nameOffile;
string text;
string mytext;
cout << "Enter name of file" << endl;
cin >> nameOffile
myfile.open(nameOffile.c_str());
if (!myfile)
{
cerr << "error abort" << endl;
exit(1);
}
while (myfile >> text )
{
Push(mytext); //Note I know this is wrong I just don't know how to write it in a manner that will push the first element of the textfile to the top
}
myfile.close();
while(hero[count]=="")
{
//Again I know these two lines are incorrect just don't know how to implement in correct manner
cout <<hero[0] << " " <<endl;
Pop(mytext);
}
}
// Function for push
void Push(string mytext)
{
count = count + 1;
hero[count] = mytext;
}
void Pop(string mytext)
{
if(count=0)
{
mytext = " ";
}
else
{
mytext = hero[count];
count = count - 1;
}
}
最佳答案
通常情况下,堆栈会以index = -1
开头,表示堆栈为空。所以你需要更换
int count = 0
与
int count = -1
完成所有推送后,您的堆栈将如下所示:
hero[0] = "Goku"
hero[1] = "Luffy"
hero[2] = "Naruto"
现在,要以相反的顺序打印出来,您可以从最后一个索引循环到第一个。压入所有英雄字符串后,count
现在等于 2。最后的英雄将位于 index = 0
。所以你可以将循环重写为
while(count >= 0)
{
cout << hero[count] << " " <<endl;
Pop();
}
您的 Pop
函数也不正确。在 if
语句中,您会将 count
的值替换为 0
。在 Pop
中您需要做的只是减少 count
的值。
所以你可以把它重写为
void Pop()
{
count = count - 1;
}
关于c++ - 如何将从文本文件中读取的元素推送和弹出到 C++ 中的数组并以相反的顺序输出堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45413095/