c++如何以空格和换行符为间隔读取文件中的字符串? 5
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;
} 展开
//给你改了下,改动的地方都有注释:
#include<stdio.h>
#include<stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
struct Course
{
char ID[5];
vector<char*>Stulist;
};
int main()
{
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;
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] ; //释放
}
}
}
运行: