如果在使用 `fscanf()` 读取字符串时如何处理 `%`
how to handle `%` if it is present in a string while reading it using `fscanf()`
假设有一个文件 a.txt
,其中每个字符串都是键值对 <key: value>
。但是一个限制是我的密钥也可以包含 %
这样的字符。例如:如下所示
string : INDIA
integer : 2015
ratio %: 20
integer2 : 2016
现在通过使用 fscanf
,我想验证文件 a.txt
.
中存在的每个字符串值
我的示例代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char str[8];
int arr[2];
FILE * fp;
int j=0;
char *out_format[4] = {
"string :",
"integer :",
"ratio %:",
"integer2 :"
};
fp = fopen ("a.txt", "r");
if (fp == NULL) {
perror( "fopen failed for input file\n" );
return -1;
}
for (j=0; j < 4; j++) {
char c[64]={'[=11=]'};
strcat(c, out_format[j]);
if (j == 0) {
strcat(c, " %s ");
fscanf(fp, c, str);
printf("%s %s\n", c, str);
}
else {
strcat(c, " %d ");
fscanf(fp, c, &arr[j-1]);
printf("%s %d\n",c, arr[j-1]);
}
}
}
编译后我收到的输出是:
string : %s INDIA
integer : %ld 2015
ratio %: %ld 0
integer2 : %ld xxxxx // some garbage
发生这种情况是因为 %
出现在文件 a.txt
的第 ratio %: 20
行中。
拜托,有人可以在这里提出建议吗?如何处理这个问题,以便我可以获得文件中存在的正确值?
您可以使用 %%
转义并匹配 %
。来自 scanf 手册页:
%
Matches a literal '%'. That is, '%%' in the format
string
matches a single input `%' character. No conversion is done,
and assignment does not occur.
用%%
代替%
即可,%%
在C语言中代表%
假设有一个文件 a.txt
,其中每个字符串都是键值对 <key: value>
。但是一个限制是我的密钥也可以包含 %
这样的字符。例如:如下所示
string : INDIA
integer : 2015
ratio %: 20
integer2 : 2016
现在通过使用 fscanf
,我想验证文件 a.txt
.
我的示例代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char str[8];
int arr[2];
FILE * fp;
int j=0;
char *out_format[4] = {
"string :",
"integer :",
"ratio %:",
"integer2 :"
};
fp = fopen ("a.txt", "r");
if (fp == NULL) {
perror( "fopen failed for input file\n" );
return -1;
}
for (j=0; j < 4; j++) {
char c[64]={'[=11=]'};
strcat(c, out_format[j]);
if (j == 0) {
strcat(c, " %s ");
fscanf(fp, c, str);
printf("%s %s\n", c, str);
}
else {
strcat(c, " %d ");
fscanf(fp, c, &arr[j-1]);
printf("%s %d\n",c, arr[j-1]);
}
}
}
编译后我收到的输出是:
string : %s INDIA
integer : %ld 2015
ratio %: %ld 0
integer2 : %ld xxxxx // some garbage
发生这种情况是因为 %
出现在文件 a.txt
的第 ratio %: 20
行中。
拜托,有人可以在这里提出建议吗?如何处理这个问题,以便我可以获得文件中存在的正确值?
您可以使用 %%
转义并匹配 %
。来自 scanf 手册页:
%
Matches a literal '%'. That is, '%%' in the format string matches a single input `%' character. No conversion is done, and assignment does not occur.
用%%
代替%
即可,%%
在C语言中代表%