2015-05-24 36 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.

相關問題