为 fscanf 指定不包含空格的格式 [英] Specifying a format for fscanf that doesn't contain white-spaces
本文介绍了为 fscanf 指定不包含空格的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 fscanf() 从 c 中的文本文件中读取名称.但是,此文件中的名称不以空格分隔.我还能用这个函数把每个名字分开吗?
I am trying to use fscanf() to read names from a text file in c. However, the names in this file are not separated by white-spaces. Can I still separate out each name using this function?
目前,该文件包含此文本:
At the moment, the file contains this text :
"MARY","PATRICIA"
当我运行以下代码时:
FILE *nameFile;
char name1[100];
char name2[100];
nameFile = fopen("names.txt","r");
fscanf(nameFile, "%s,%s", name1, name2);
printf("name 1 : %s\n name 2 :%s\n", name1, name2);
fclose(nameFile);
我得到以下输出:
name1: "MARY","PATRICIA"
name2:
有没有办法在文件中没有空格的情况下将名称分开?
Is there any way of separating the names out without having spaces in the file?
推荐答案
你必须指示 fscanf() 寻找另一个分隔符,切割字段(使用 %[ 格式化程序).
You have to instruct the fscanf() to look for another delimiter, cutting the fields (using %[ formatter).
请试试这个:
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *nameFile;
char name1[100];
char name2[100];
nameFile = fopen("names.txt","r");
fscanf(nameFile, "%[^,],%[^,]\n", name1, name2);
/* or fscanf(nameFile, "%[^,],%s\n", name1, name2); for second string */
printf("name 1 : %s\n name 2 :%s\n", name1, name2);
fclose(nameFile);
return(0);
}
这篇关于为 fscanf 指定不包含空格的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文