我需要读取一个看起来像这样的格式化文件。
代码:HARK
姓名:奥斯卡
MRTE:火车
ETC
目前我的代码看起来像这样。
FILE *file;
char unneeded[10];
char whitespace[2];
char actual[10];
file = fopen("scannertest.txt","r");
fscanf(file,"%s",unneeded); // this is the identifier and the colon (code:)
fscanf(file,"%[ ]",whitespace); // this takes in the white space after the colon.
fscanf(file,"%s",actual); // this is the value I actually need.
/**
* Do stuff with the actual variable
**/
fclose(file);
这种方法对我有用,但我不认为为文本文件中的每一行编写三个 fscanf() 是最好的方法,特别是因为我稍后将在循环中这样做。
我试着这样做:
fscanf(file, "%s %[ ] %s",unneeded,whitespace,real);
然而,当我尝试打印输出时,这给了我奇怪的符号。