注册 登录
编程论坛 C++教室

各位帮小弟分析一下~!

lionmusicyj 发布于 2008-09-30 23:27, 597 次点击
void add_data(student stu[])
{
     char flag;
     student add_stu;
     cin>>add_stu.num;
     cin>>add_stu.name;
     cin>>add_stu.sex;
     ofstream out_cfile("sstu.txt",ios::app);
     out_cfile<<add_stu.num<<'\t';           //  \t使输入数据和文件的格式相同
     out_cfile<<add_stu.name<<'\t';
     out_cfile<<add_stu.sex;
     cout<<"Do you want continue?(Y or N) ";
     cin>>flag;
     if(flag=='y'||flag=='Y')
       add_data(stu);
}
这个函数是为了给文本文件添加数据的,代码编译是可以通过的,但是在文件下显示是倒序输入的,比如:输入   1 李航 男   2 陈晨 女,但是在文本文件下显示是 2 陈晨 女     1 李航 男  ,郁闷~!这是不是和栈的概念有关哪?但是该怎么控制呢??请各位赐教~!
8 回复
#2
blueboy820062008-10-01 08:05
应该与栈有关吧...
但还应该与流有关吧...没研究过...  从程序来看,不应该倒序的...
其实,你完全可以用结构体数组控制...
何必在add_data中又调用了add_data呢...
#3
p1s2008-10-01 10:06
你用了递归,输出的当然就倒过来了。我觉得是否继续读取应该放在这个函数体外来控制,这个函数体只负责读取和输出文件。

关于递归是怎么造成这样的后果,我的《易学C++》第12章讲递归的时候正好有一个类似的例子,我贴出来给你看一下:

//程序12.3.1 模拟栈
#include <iostream>
using namespace std;
void stack(char c);
int main()
{
    char d;
    cin >>d;
    stack(d);
    cout <<endl;
    return 0;
}
void stack(char c)
{
    if (c!='#')            //判断是否输入结束
    {
        char d;
        cin >>d;            //没有结束则继续输入数据
        stack(d);            //继续判断输入的数据
        cout <<c;            //待输入结束则将字符输出
        return;            //返回调用处,去输出上一个字符
    }
    else
    {
        return;
    }
}
运行结果:
ABCD#
DCBA
#4
守鹤2008-10-01 14:02
void add_data(student stu[])
{
     char flag;

cin>>flag;

while(flag=='Y'||flag=='y')
     student add_stu;
     cin>>add_stu.num;
     cin>>add_stu.name;
     cin>>add_stu.sex;
     ofstream out_cfile("sstu.txt",ios::app);
     out_cfile<<add_stu.num<<'\t';                    

     out_cfile<<add_stu.name<<'\t';
     out_cfile<<add_stu.sex;
     cout<<"Do you want continue?(Y or N) ";
     cin>>flag;
}
#5
lionmusicyj2008-10-01 15:55
呵呵~!谢谢各位回答了~小弟收益非浅~!!!!
真的谢谢大家~!
#6
God_WangY2008-10-01 17:00
文件使用完没有关闭
在缓存中是栈的形式,所以是倒得
要是加上out_cfile.close()就是顺序的
#7
lionmusicyj2008-10-01 23:22
GOD哥哥
可以再说清楚一点吗?
文件关闭应该放在哪呀?
#8
lionmusicyj2008-10-01 23:29
高手呀~!
一语点醒梦中人,收我做徒弟吧~!
这个问题捆扰我两天了,今天得以解决,心情相当激动~!
#9
kevin882008-10-02 01:22
路过,刚好在学递归,感谢大家!
1