我在声明ifstream
对象的行上收到错误:
ifstream input;
或
ifstream input("somefile");
这将在第一次正常工作,但是下一次循环之前的行会发生运行时错误!
以下是完整的程序源代码:
#include<conio.h>
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<iomanip.h>
#include<ctype.h>
class SV
{
private:
char Name[30];
char Gender[7]; //Try setting the bound of this array to 3 and see what will happen to the value of GioiTinh whenever we assign a string to it
char BirthDay[10];
char HomeTown[40];
char CurrentLocation[40];
char SchoolYear[5];
char Course[20];
char Qualification[10];
float AverageMark;
SV * next;
public:
int Nhap()
{
char * info[9];
int i;
SV * newSV = new SV;
SV * q = new SV;
strcpy(Name, "");
//-----------------------
for(i = 0; i < 9; i++)
info[i] = new char[50];
i = 0;
ifstream input("Student.INP"); // <--- I'm stuck here
if(input.bad())
{
cout<<endl<<"The file \"Student.INP\" doesn't exist in the folder of the program!!!";
return -1;
}
do
{
char s[255];
i = 0;
input.getline(s,255);
int j = 0;
int k = 0;
do
{
if(s[j] == '\0')
{
info[i][k] = '\0';
break;
}
if(s[j] == '|')
{
info[i][k] = '\0';
k = 0;
i++;
j++;
continue;
}
info[i][k] = s[j];
k++;
j++;
}while(j < 255);
strcpy(newSV->Name,info[0]);
strcpy(newSV->Gender,info[1]);
strcpy(newSV->BirthDay,info[2]);
strcpy(newSV->HomeTown , info[3]);
strcpy(newSV->CurrentLocation,info[4]);
strcpy(newSV->SchoolYear,info[5]);
strcpy(newSV->Course,info[6]);
strcpy(newSV->Qualification,info[7]);
newSV->AverageMark = atof(info[8]);
newSV->next = NULL;
if(strcmp(Name, "") == 0)
{
*this = *newSV;
next = q;
}
else
{
*q = *newSV;
if(!input.eof())
{
q->next = new SV;
q = q->next;
}
else
{
q->next = NULL;
delete q;
break;
}
}
}while(1);
input.close();
delete info;
delete newSV;
return 0;
}
//There are more functions ...
};
//The main entry point of the program
void main()
{
do
{
QLSV();
cout<<endl<<"Press any key to continue ...";
getch();
}while(1);
}
以下链接可能有所帮助:
如果我使用FILE指针代替(C)ifstream(C ++),我可以“更长时间”运行程序,但有时错误也指向FILE * f = fopen("somefile", "r");
。