c++如何以空格和换行符为间隔读取文件中的字符串?

2025-03-22 01:10:42
推荐回答(1个)
回答1:

//给你改了下,改动的地方都有注释:

#include

#include

#include

#include

using namespace std;

struct Course

{

char ID[5];

vectorStulist;

};

int main()

{

vectorvecCourse;

FILE *pfile = NULL;

fopen_s(&pfile, "d:\\data_stu\\coursemember.txt", "r");

if (pfile == NULL)

{

printf("error!\n");

exit(0);

}

Course course;

char *stuname;

char buffer[200];  //临时空间

while (1)

{

fscanf_s(pfile, "%s", course.ID, 5);

if (feof(pfile)) break;

while (1)

{      

char ch = fgetc(pfile);

if (ch != '\n')

{

fscanf_s(pfile, "%s", buffer);   //先读到buffer里

stuname = new char[strlen(buffer)+1];  //申请适当的空间

strcpy(stuname, buffer);     //复制

course.Stulist.push_back(stuname);

}

//delete stuname;  //这就是vecCourser里的链接,不能释放

if (ch == '\n') break;

}

vecCourse.push_back(course);

course.Stulist.clear();  //清理临时course

}

fclose(pfile);


for (unsigned int i = 0; i < vecCourse.size(); i++)

{

cout << vecCourse[i].ID << "\t";

unsigned int j = 0;

for (; j < vecCourse[i].Stulist.size(); j++)  //不-1

{

cout << vecCourse[i].Stulist[j] << " ";

}

cout << endl;  //换行

}

for (unsigned int i = 0; i < vecCourse.size(); i++)

{

unsigned int j = 0;

for (; j < vecCourse[i].Stulist.size(); j++)  

{

delete[] vecCourse[i].Stulist[j] ;   //释放

}

}

}

运行: