こんにちは私はC++を初めて使っていて、要素をテキストファイルから配列に読み込んでポップアップする方法と、逆の順序で要素を表示する方法を理解するのに問題があります。例えば、要素があるhero.txtというテキストファイル悟空ルフィナルトが、私はこれは私がこれまでテキストファイルから読み込んだ要素をC++で配列にプッシュしてポップし、スタックをrevserse順に出力する方法はありますか?
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;
}
}
はhttp://en.cppreference.com/w/cpp/container/stackを参照してください。テンプレート化されたクラスなので、 'std :: stack mystack'と宣言すると、それを' mystack.push(mystring); 'として使うことができます。ところで、あなたは 'text'と' mytext'を持っていて、それらを混在して使いました。確かにそれはただのものだったはずです。 –
patatahooligan
こんにちはありがとうが、私はまだC++に新しいので、テンプレートクラスを使用しないようにしたい – DaLOLZ
悲しいことに、これはスタックの標準実装です。実際にはそれほど難しいことではありません。宣言は、書かなければならないテンプレートインスタンス化の唯一の行です。他のすべての行について、他のクラスと同様に動作します。実際に使用したくない場合は、独自の 'StringStack'クラスを書く機会があります。 – patatahooligan