【发布时间】:2018-01-06 20:39:52
【问题描述】:
您好,我是 C++ 新手,我无法理解如何将从文本文件读取的元素推送和弹出到数组并以相反的顺序显示这些元素,例如,如果我有一个名为 hero.txt 的文本文件元素悟空路飞火影忍者我希望输出是火影忍者路飞悟空 这就是我到目前为止所拥有的
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;
}
}
【问题讨论】:
-
见en.cppreference.com/w/cpp/container/stack。这是一个模板类,因此在将其声明为
std::stack<std::string> mystack后,您可以将其用作mystack.push(mystring);。顺便说一句,您有text和mytext,并且您以混合方式使用它们。当然它应该只是一个。 -
您好,谢谢,但我想避免使用模板类,因为我还是 C++ 新手
-
遗憾的是,这是堆栈的标准实现。实际上,这并不难。声明是您必须编写的模板实例化的唯一行。对于其他每一行,它将表现得与任何其他类一样。如果实在不想用,可以趁机编写自己的
StringStack类。