C++将数据从堆栈放入文件

C++将数据从堆栈放入文件,c++,C++,我还没有太多的C++知识,我想请求帮助完成一项任务。我必须创建一个堆栈,其中填充了键盘输入的数据,并将整个堆栈写入外部堆栈。我制作了函数push、pop和简单程序来显示堆栈,但在此之前,数据必须写入外部文件。有人能帮我处理这个外部文件吗 #include <iostream> #include <iomanip> #include <stdlib.h> using namespace std; struct elem { int key; elem *nex

我还没有太多的C++知识,我想请求帮助完成一项任务。我必须创建一个堆栈,其中填充了键盘输入的数据,并将整个堆栈写入外部堆栈。我制作了函数push、pop和简单程序来显示堆栈,但在此之前,数据必须写入外部文件。有人能帮我处理这个外部文件吗

#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;

struct elem
{ int key; elem *next;} *start=NULL, *p;


void push(int n)
{
    p=start;
    start=new elem;
    start->key=n;
    start->next=p;}

    int pop(int &n){
    if (start)
    {
        n=start->key;
        p=start;
        start=start->next;
        delete p;
        return 1;
    }
    else
        return 0;

}

int main(){
    int num;
    cout<<"Input integers:"<<setw(10);
    while (cin>>num)
    {
        push(num);
    }
    cout<<endl<<"Stack:"<<endl;
    while(pop(num))
    {
         cout<<num<<endl;
    }
    return 0;
}

//您可以使用这个伪代码

ofstream outFile;

while(start!=-1){
    outFile << pop() << endl;

您希望在堆栈中包含一个函数,例如导出,将其数据打印到文件中,对吗?堆栈是一个单链表,如果您可以遍历此类列表,则您知道如何遍历堆栈。然后,您知道如何写入std::cout,写入其他输出流也是一样的。现在,结合这两个概念,您就有了解决方案。如果您已经了解iostream,那么fstream的处理方式与iostream类似,但可以处理文件。看见