我从文本文件中读取了一些数据,我试图逐行迭代并以逗号分隔,但我忽略了以#
开头的行,这是文本文件的内容:
#这是您练习的模拟文件,请仔细阅读。
#以英镑符号开头的每一行[现在称为#标签(#)]都是注释行。您可以自动跳过它。
#这是一些示例。
#将有5个类别:喜剧,冒险,教育,科幻,幻想。 #建议您保存在主程序中时,请遵循此对流。 #输入语法: #id,书名,作者,页面,出版年份,类别 CNV301,金银岛,罗伯·路易斯·史蒂文森,304,1882,冒险 8T88FF,帝国继承人,蒂莫西·扎恩,416,1992,科幻 911MAR10,傻瓜水暖工程,基因·汉密尔顿,242,1999,教育 6U754E,Berserk,Kenturo Miura,224,1989,Fantasy 7R011,The Troll Cookbook:Human Delights,Underchief Trogdor,7,-35,Educational M140,Funny Cats,Jean-ClaudeSuarès,78,1995,Comedy V269W7,雷纳斯·雷纳斯·雷纳斯(Robert Linbecker),40,2013,冒险 UFF404,代数3,Nebi Rogen,300,0,教育 424242,《银河系漫游指南》,道格拉斯·亚当斯(Douglas Adams),224,1979年,喜剧
#添加您自己的。您可以使用http://www.generatedata.com/之类的网站来创建快速列表。
这是我的代码:
FILE* file = fopen(filepath, "r");
char line[256] = "";
while (fgets(line, sizeof(line), file) != NULL) {
if (!starts_with(line, "#") && !starts_with(line, " "))
{
if (line[0] == '#' || line[0] == '\n')
continue; // skip the rest of the loop and continue
printf("%s", line);
char* p;
p = strtok(line, ",");
while (p != NULL)
{
//printf("%s\n", p); //<-- line*******
p = strtok(NULL, ",");
}
}
}
fclose(file);
其中:
int starts_with(const char* line, const char* c)
{
size_t lenpre = strlen(c),
lenstr = strlen(line);
return lenstr < lenpre ? 0 : strncmp(c, line, lenpre) == 0;
}
运行代码时,我在第一行打印一些奇怪的字符,例如:
#this is the simulation file for your exercise, please read it carefully.
如果启用以下注释行:
//<-- line*******
我收到错误消息:“访问冲突读取位置”,我只想查看拆分的值