我必须解析像这样的.txt文件
autore: sempronio, caio; titolo: ; editore: ; luogo_pubblicazione: ; anno: 0; prestito: 0-1-1900; collocazione: ; descrizione_fisica: ; nota: ;在C代码中使用fscanf。我在fscanf调用中尝试了一些格式,但没有一种有效.
编辑:
A= fscanf(fp,"autore:%s");
这是我做的第一次尝试,fscanf()不可能捕捉到'autore‘、'titolo’、'editore‘等图案。
发布于 2012-07-01 14:36:46
一般来说,尝试用fscanf解析输入不是一个好主意,因为如果输入不符合预期,就很难优雅地恢复。通常最好将输入读入内部缓冲区(使用fread或fgets),并在其中解析它(使用sscanf、strtok、strtol等)。关于哪些函数最好的详细信息取决于输入格式的定义(您没有给出这种定义;示例输入不能替代正式的规范)。
发布于 2012-07-01 16:23:35
下面展示了如何使用strtok
char* item;
char* input; // fill it with fgets
for (item = strtok(input, ";"); item != NULL; item = strtok(NULL, ";"))
{
// item loops through the following:
// "autore: sempronio, caio"
// " titolo: "
// " editore: "
// ...
}下面展示了如何使用sscanf
char tag[20];
int chars = -1;
if (sscanf(item, " %19[^:]: %n", tag, &chars) == 1 && chars >= 0)
{
printf("%s is %s\n", tag, item + chars);
}在这里,格式字符串由以下内容组成:
如果有意外输入,则不会更新字符数,因此在解析每个项之前,必须将其设置为-1。
https://stackoverflow.com/questions/11282784
复制相似问题