2015-05-14 30 views
0

我想從文件中取詞,並將其發送給數組。我用fscanf做了這個。但是,它正在考慮數字,字符(以及其他內容)。我怎樣才能控制這種說法?C - 我如何從沒有數字,特殊字符(,。?&)的文件中取詞?

int main(void) 
{  
    char path[100]; 
    printf("Please, enter path of file: "); scanf("%s",&path); 
    FILE *dosya; 
    char kelime[1000][50]; 
    int i=0; 

    if((dosya = fopen(path,"r")) != NULL) 
    { 
    while(!feof (dosya)) 
    { 
     fscanf(dosya,"%s",&kelime[i]); 
     i++; 
    } 
    } 
    else{printf("Not Found File !");} 
    fclose(dosya); 
} 
+3

不要使用'while(!feof(...))',它在大多數情況下不會按預期工作。使用例如'while(fscanf(dosya,「%s」,&kelime [i])== 1)'。 –

+2

至於你的問題,你可能會發現[這個'scanf'(和家庭)引用](http://en.cppreference.com/w/c/io/fscanf)有用,特別是關於''%[ 「'格式。 –

+0

順便說一句'fclose'應該在'if ...!= NULL'檢查中。一些(大多數?)系統在關閉「NULL」時會崩潰。 – anatolyg

回答

-1

當您使用fscanf()語句無法解析您可以使用fgetc()

char str[1000]; 
while((ch=fgetc(fname))!=EOF) 
{ 
     // Write your code here; 
     if((ch>='0' && ch<='9') || (ch<'a' && ch>'z') || (ch<'A' && ch>'Z')) 
       continue; 
     str[i++]=ch; 
} 
str[i]='\0'; 

。所以,你必須

  1. 檢查它通過炭炭

  2. 如果沒有特殊字符或數字,然後添加到字符串

+0

你沒有指出這是怎麼回事幫助OP排除他正在避開的角色。 –

+0

@DavidHoelzer現在好嗎? – Subinoy

2

使用"%[]"字母和非字母來區分。

#define NWORDS (1000) 
char kelime[NWORDS][50]; 

size_t i; 
for (i=0; i<NWORDS; i++) { 
    // Toss ("*" indicates do not save) characters that are not ("^" indicates `not`) letters. 
    // Ignore return value 
    fscanf(dosya, "%*[^A-Za-z]"); 

    // Read letters 
    // Expect only a return value of 1:Success or EOF:no more file to read 
    // Be sure to limit number of characters read: 49 
    if (fscanf(dosya, "%49[A-Za-z]", kelime[i]) != 1) break; 
} 

// do something with the `i` words 
相關問題