2014-10-09 94 views
0

我正在嘗試讀取文件並打印文件中的所有單詞,忽略所有其他空格和符號。我有它與strcpy工作,但它給了我一個錯誤,我試圖使用sprintf,但我真的不明白如何功能的話。它打印隨機整數而不是字符串。添加int到字符串時遇到問題,嘗試使用sprintf但我遇到了問題

編輯:我對C完全陌生,所以我沒有把我的指針搞得太好。

FILE *file; 
    file = fopen("sample_dict.txt", "r"); 
    int c; 
    int wordcount = 0; 
    int count = 0; 
    const char *a[10]; 
    char word[100]; 
    do { 
    c = fgetc(file); 
    //error statement 
    if (feof(file)) { 
     break; 
    } 
    if (isalpha(c) && count == 2) { 
     printf("%s\n", word); 
     memset(word, 0, sizeof(word)); 
     count = 1; 
     wordcount++; 
    } 

    if (isalpha(c)) { 
     //strcat(word, &c); 
     sprintf(word, "%d", c); 
     continue; 
    } 
    count = 2; 
    continue; 
    } while (1); 
    fclose(file); 
    return (0); 

    return 0; 
+0

使用'%D'就可以打印它是這樣的,當打印'char'爲整);'但是你重置每個字符中的單詞。更好地使用計數器並複製到數組中... – SHR 2014-10-09 23:54:05

回答

1

如果您需要字符,請在%C中使用%c作爲格式說明符。如果您使用%d,它將起作用,但會顯示爲整數。
的另一件事是,如果你想用sprintf來連接一個字符的字符串,或和INT,你必須包括在sprintf的參數列表:

改變這一點:

sprintf(word, "%d", c); 

要這樣:

char newString[20];//adjust length as necessary 
sprintf(newString, "%s%c",word, c); 

在這裏你的邏輯表明您只需要追加字符,如果是阿爾法即[az,AZ]

if(isalpha(c)) 
    { 
    //strcat(word, &c); 
    sprintf(word, "%d", c); 
    continue; 
    } 

將其更改爲:`sprintf的(字, 「%C」,C:

if(isalpha(c)) 
    { 
    //strcat(word, &c); 
    char newString[20];//bigger if needed, 20 just for illustration here 
    sprintf(newString, "%s%d", word, c); 
    continue; 
    }  
+0

我將其更改爲 sprintf(單詞「%s%c」,單詞c); 它工作。謝謝 – Kot 2014-10-10 00:02:52

+1

'sprintf(word,「%s%d」,word,c);'是UB。因爲sprintf第一個參數是'restrict'(複製區域重疊區域行爲未定義)。 – BLUEPIXY 2014-10-10 09:32:40

+0

@BLUEPIXY - 你是對的。謝謝。編輯後。 – ryyker 2014-10-10 15:33:46

0
#define IN 1 
#define OUT 0 

FILE *file; 
file = fopen("sample_dict.txt","r"); 
int c; 
int wordcount = 0; 
int status = OUT;//int count = 0; 
//const char *a[10];//unused 
char word[100] = ""; 

do { 
    c = fgetc(file); 
    if(feof(file)){ 
     if(*word){//*word : word[0] != '\0' 
      printf("%s\n", word); 
     } 
     break; 
    } 
    if(isalpha(c)){ 
     char onechar_string[2] = {0};//{c}; 
     onechar_string[0] = c; 
     strcat(word, onechar_string); 
     if(status == OUT){ 
      wordcount++; 
     } 
     status = IN; 
    } else { 
     if(status == IN){ 
      printf("%s\n", word); 
      *word = 0;//memset(word,0,sizeof(word)); 
     } 
     status = OUT; 
    } 
}while(1); 
fclose(file);