2016-05-31 107 views
0

如何避免閱讀分號;在FILE中並將它們保存在變量中?如何忽略';'在fscanf文件中?

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
int main(void) 
{ 
char gstitem[6], gstname[30],; 
int gstquant, itemquant; 
float gstprice; 

char string[10]; 
printf("Purchase items fuction\n\n"); 
FILE *gstPtr; //pointer to the gst.txt 
gstPtr = fopen ("gst.txt", "r+"); 
printf("Enter an item code: "); 
fgets(string,10,stdin); 
(!feof(gstPtr)); 
{ 

    fscanf(gstPtr,"%[^;]s %[^;]s %[^;]f %[^;]d\n",gstitem,gstname,&gstprice,&gstquant); 
    printf("%s %s %f %s\n",gstitem,gstname,gstprice,gstquant); 
    } 
fclose(gstPtr); 
} 

這是我想FSCANF VV

gst.txt

+0

您的圖片文字少量:請張貼文字作爲問題的一部分。 [Minimal,Complete,and Verifiable example](http://stackoverflow.com/help/mcve)的思想是讓讀者可以複製和嘗試代碼及其輸入數據。 –

+1

不檢查'fscanf()'的結果是[_Road to Perdition_](http://www.dictionary.com/browse/perdition), – chux

+0

循環之前'fgets'的目的是什麼?什麼是循環控制'(!feof(gstPtr));'[原文如此]?除了謹慎使用[feof'](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)之外,控制循環的方法是返回(fscanf(...)== 4){...}' –

回答

3

與格式字符串問題的文件:

  1. 當您使用%[^;]格式說明,你不應該將s添加到它。這意味着預期的數據是字符串。

  2. 使用%[^;]沒有指定寬度會導致讀取更多的數據比您的變量可以容納。始終指定您希望讀取的最大字符數。

  3. 使用%[^;]d%[^;]f不允許你閱讀intfloat

  4. 避免在格式字符串中使用\n。這將導致fscanf讀取並放棄所有字符,直到下一個非空白字符。它不會只讀取換行符。最好添加另一行以跳過所有內容,直到包括換行符。

用途:

fscanf(gstPtr,"%5[^;];%29[^;];%f;%d",gstitem, gstname, &gstprice, &gstquant); 
int c; 
while ((c = fgetc(gstPtr)) != EOF && c != '\n'); 
+2

無限寬度說明符如''%[^;]「'和'gets()'差不多。 – chux

+1

@chux的確如此。感謝指針。 –