我用c++语言来做文件操作,例如写入和读出的操作,但是当输入完数据之后,就进入死循环了,请各位高手帮忙

#include "stdafx.h"#include<fstream.h>#include"iostream.h"#include"stdlib.h"void enter(char *filename){ char name[30],flag=✀y✀; int number,score; ofstream outstuf; outstuf.open(filename,ios::out); if(!outstuf) {cerr<<"file could not be open"<<endl; abort(); } outstuf<<"this is a file of students尀n"; cout<<"请输入: number ,name ,an score: (enter Ctrl+z to end intput)尀n"; while (cin>>number>>name>>score) { outstuf<<number<<✀尀t✀<<name<<✀尀t✀<<score<<✀尀n✀; } outstuf.close(); }void display(char*filename){ char name[30]; int number,score; ifstream instuf(filename,ios::in); if(!instuf) {cerr<<"file could not be open"<<endl; abort(); } char s[80]; instuf.getline(s,80); while(instuf>>number>>name>>score) {cout<<number<<✀尀t✀<<name<<✀尀t✀<<score<<✀尀n✀; } instuf.close();}void interfaced(void){ cout<<"文件复习:尀n"; cout<<"=======================================尀n"; cout<<" 输入纪录-----------------0尀n"; cout<<" 查询纪录-----------------1尀n"; cout<<" 退出---------------------2尀n"; cout<<"=======================================尀n"; cout<<"请输入数字(0--2):尀n";}void main(){for(;;){ char filename[30]; int i; cout<<"please input the name of student`s file"<<endl; cin>>filename; interfaced(); cin>>i; switch(i) { case 0: enter(filename); break; case 1: display(filename); break; case 2: exit(0); default : cout<<"警告!!!请输入数字0-2!尀n"; ) }}} 问题补充:我用for语句主要是想当把数据输入完之后,再回到主界面,然后继续其他操作,如:显示操作,如果不用for我就不用在这问这问题了,因为我也试过,不用for就直接输入完数据就结束了。 //我用的环境是VC6.0。//“i”不是定义为整型数据吗?会变成ASCII的50?//
2026年09月22日 15:43
有1个网友回答
网友(1):

自问自答,正解为:
#include "stdafx.h"

#include

#include"iostream.h"

#include"stdlib.h"

void enter(char *filename,int n)

{ char name[30],flag='y';

int number,score;

ofstream outstuf;

outstuf.open(filename,ios::out);

if(!outstuf) {cerr<<"file could not be open"<
outstuf<<"this is a file of students\n";

cout<<"请输入: number ,name ,an score: (enter Ctrl+z to end intput)\n";
int i=n;
do
{i--; cin>>number>>name>>score;
outstuf<}while(i!=0);
outstuf.close(); }

void display(char*filename)

{ char name[30]; int number,score;

ifstream instuf(filename,ios::in);

if(!instuf) {cerr<<"file could not be open"<
char s[80]; instuf.getline(s,80);

while(instuf>>number>>name>>score)

{cout<
instuf.close();}

void interfaced(void){ cout<<"文件复习:\n"; cout<<"=======================================\n";

cout<<" 输入纪录-----------------0\n";

cout<<" 查询纪录-----------------1\n";

cout<<" 退出---------------------2\n";

cout<<"=======================================\n";

cout<<"请输入数字(0--2):\n";}

void main()

{

char filename[30]; int i,n;

cout<<"please input the name of student`s file"<
cin>>filename;
do
{j:interfaced();
i=NULL;
cin>>i;
if(i!=0&&i!=1&&i!=2)
{cout<<"please enter a right number!!!";
goto j;}
else
switch(i)
{
case 0: cout<<"输入多少个人的数据呢?"< cin>>n;enter(filename,n);i=NULL;goto j;

case 1: display(filename);i=NULL;goto j;

case 2: exit(0);

default : cout<<"警告!!!请输入数字0-2!\n";i=NULL; goto j;

}
}while(i!=2&&i!='2');
}