2013-05-05 57 views
0

我正在編寫代碼,我需要使用循環。我正在從一個文件(data.txt)讀取數據,如下所示:循環無法識別C中的字符串

IMPORT 450 

EXPORT 200 

IMPORT 100 

等等。

這裏是我有

inputfile = fopen("c:\\class\\data.txt","r"); 
fscanf(inputfile,"%s %f", &transaction, &amount); 

do{     
    total += amount;    
    printf("Data %s %f %f\n", transaction, amount, total); 
    fscanf(inputfile, "%s", &transaction); 

}while (transaction == "IMPORT" || transaction == "EXPORT"); 

麻煩當我添加一個printf線檢查什麼「交易」,因爲它顯示導入代碼段,所以我不知道爲什麼做 - while循環不重複。

謝謝!

回答

4

假設transactionchar陣列,比較

transaction == "IMPORT" 

將比較transaction地址針對字符串文字"IMPORT"的地址。

您需要使用

while (strcmp(transaction, "IMPORT") == 0 || 
     strcmp(transaction, "EXPORT") == 0) 

在C.

1

是什麼類型transaction比較字符串?

爲了與fscanf%s運營商很可能是char[],並用它在你需要使用strcmp這種情況下; ==運算符將比較字符指針地址,而不是內容。

0

當您嘗試檢查事務==「IMPORT」時,C僅比較第一個字符的指針。這真的很好。也許試試這個代碼:

int str_equal(char* str1, char* str2) 
{ 
    int i, len; 

    if ((len = strlen(str1)) != strlen(str2)) 
    { 
     return 0; 
    } 

    for (i = 0; i < len; i++) 
    { 
     if (toupper(str1[i]) != toupper(str2[i])) 
    { 
      return 0; 
     } 
    } 

    return 1; 
} 
0

大概就是這個樣子

while(2==fscanf(inputfile,"%s %f", transaction, &amount)){ 
     if(strcmp("IMPORT", transaction)==0) 
      total += amount; 
     else if(strcmp("EXPORT", transaction)==0) 
      total -= amount; 
     else 
      break; 
     printf("Data %s %f %f\n", transaction, amount, total); 
    }