2015-05-24 56 views
2

假设有一个文件a.txt,其中每个字符串都是一个键值对,如<key: value>。但一个限制是我的密钥也可能包含像%这样的字符。例如:下面如果在使用`fscanf()读取字符串时存在`%``

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]={'\0'}; 
     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]); 
     } 
    } 
} 

输出I编译后收到的是:

string : %s INDIA 
integer : %ld 2015 
ratio %: %ld 0 
integer2 : %ld xxxxx // some garbage 

这是发生由于%存在于文件a.txtratio %: 20线。

请问,有人可以在这里建议吗?如何处理这个问题,以便我能够得到文件中存在的正确值?

+2

它看起来像'C [12]'是'因为“整数2太小的数组:“'是10个字符,而'%s”是另一个4,所以'c'应该有15个字符的空间,包括尾部零。 –

+0

这一行:'if(fp <0){'应该是:'if(fp == NULL){'因为比较指向整数的指针无效。和fopen()返回一个指针,而不是数字(你的编译器应该告诉你这一点)。建议在编译时启用所有警告。 (对于gcc,至少使用:'-Wall -Wextra -pedantic') – user3629249

+0

这一行:'char c [64] = {};'应该是:'char c [64] = {'\ 0'};'因为否则,不执行初始化。 (你的编译器应该告诉你这个) – user3629249

回答

7

您可以使用%%来简化并匹配%。从scanf函数手册页:

匹配字符 '%'。即,格式为 的'%%'字符串 与单个输入'%'字符匹配。没有转换完成, 和分配不发生。

手册:http://www.manpages.info/linux/scanf.3.html

0

只需使用%%更换%%%是代表字面%在C.