檔案中的字串排列方式如下:
001 student2 student1
003 student2 student1 student3
008 student3
想要讀取到如下vector中:
struct Course
{
char ID[5];
vector<char*>Stulist;
};
vector<Course>vecCourse;
以下代碼執行后無輸出,感覺是讀換行符那邊出了點問題,但不知道怎么改
FILE *pfile = NULL;
fopen_s(&pfile, "d:\\data_stu\\coursemember.txt", "r");
if (pfile == NULL)
{
printf("error!\n");
exit(0);
}
Course course;//新建一個Course型變數用于臨時存放檔案中讀出的資料
char *stuname;
while (1)
{
fscanf_s(pfile, "%s", course.ID, 5);
if (feof(pfile)) break;//檔案結束退出回圈
while (1)
{
char *stuname = new char;//確保每次push進Stulist的地址不同
char ch = fgetc(pfile);
if (ch != '\n')//判斷是否換行
{
fscanf_s(pfile, "%s", stuname);
course.Stulist.push_back(stuname);
}
delete stuname;
if (ch == '\n') break;//退出內層回圈
}
vecCourse.push_back(course)//;將course推入vector
}
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()-1; j++)
{
cout << vecCourse[i].Stulist[j] << " ";
}
cout << vecCourse[i].Stulist[j] << endl;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/98862.html
標籤:C++ 語言
