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

C++ put data from stack to file

本文关键字:文件 堆栈 数据 C++      更新时间:2023-10-16

我仍然没有太多的C++知识,我想为一项任务寻求帮助。我必须创建一个堆栈,其中填充了键盘输入的数据和整个堆栈以写入外部堆栈。我已经制作了显示堆栈的函数推送、弹出和简单的程序,但在此之前数据必须写入外部文件。任何人都可以帮我处理外部文件吗?

#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;