2014-04-01 27 views
0

我有一個簡單的程序,讀取所有文本文件的字符和閱讀過程中,它排除一些字符。如何比較C中文字的字符?

下面一個例子,以明確

這是我的txt文件的內容:

a b c d e e 
f g d h i j 
d d d e e e 

我想刪除字符「d」和空間之後,它得到這樣的結果:

a b c e e 
f g h i j 
e e e 

我的程序讀取後未刪除字符'd'及其空格。

這是我用來打開和閱讀txt文件的代碼:

#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc, char *argv[]) 
{ 
    if(argc==2) 
    { 
     FILE *file; 
     file = fopen(argv[1], "r"); 
     int c; 
     char x = ' '; 

     if (file == NULL) 
     { 
      printf("Error\n"); 
      return 1; 
     } 

     while(x != 'd') 
     { 
      c = fgetc(file); 
      if(feof(file)) 
      { 
       break ; 
      } 
      printf("%c", c); 
     } 

     fclose(file); 
    } 
    return 0; 
} 
+0

您沒有在while循環中設置'x'值。 –

回答

1

只需使用一個if的條件打印。

同時,讓你的無限循環明顯。

+0

它刪除了字符'd',但是如何刪除'd'後的空格? –

+1

只需在其他部分添加一個fgetc? – Deduplicator

+0

謝謝,它的工作原理。 –

1

你可以簡單地做一個龜etc跳過空間。

#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc, char *argv[]) 
{ 
    if(argc==2) 
    { 
     FILE *file; 
     file = fopen(argv[1], "r"); 
     int c; 

     if (file == NULL) 
     { 
      printf("Error\n"); 
      return 1; 
     } 

     while((c = fgetc(file)) != EOF) 
     { 
      if(c == 'd') 
      { 
       fgetc(file); // Skip space 
      } 
      else 
      { 
       printf("%c", c); 
      } 
     } 

     fclose(file); 
    } 
    return 0; 
} 
+0

這是爲了學習...? – Deduplicator

+0

哇,這也適用了。謝謝。 –