文本文件包含: 「由查爾斯·達爾文我想從文件中讀取包含段落文本,分詞,然後分配到一個數組
從雙城記開幕這是最好的時代,這是最壞的時代,這是時代的智慧 ,這是愚蠢的時代。那是 信仰的時期,那是懷疑的時期「。
我不知道我錯在哪裏。
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define max_words 20
#define max_story_words 1000
#define max_word_length 80
int main()
{
char story[max_story_words][max_word_length],ch;
int num_words=1;
FILE *file_story=fopen("TwoCitiesStory.txt", "r");
if (file_story==NULL)
printf("Unable to open %s\n","TwoCitiesStory.txt");
else{
ch=fgetc(file_story);
while(ch!=EOF){
if(ch==' '||ch=='\n')
num_words++;
ch=fgetc(file_story);
}
int i=0;
//assigning each words to story[i]
while (i<max_story_words && fgets(story[i], max_word_length, file_story) != NULL) {
if(story[i][strlen(story[i])-1]=='\n'||story[i][strlen(story[i])-1]==' '||story[i][strlen(story[i])-1]==','||
story[i][strlen(story[i])-1]=='!'||story[i][strlen(story[i])-1]=='.'||story[i][strlen(story[i])-1]==':'||
story[i][strlen(story[i])-1]==';'||story[i][strlen(story[i])-1]=='?'||story[i][strlen(story[i])-1]=='-'||
story[i][strlen(story[i])-1]=='?')
//remove a newline here
story[i][strlen(story[i])-1]='\0';
i++;
}
for(int i=0;i<num_words;i++){
printf("story[%d]: %s\n",i,story[i]);
}
printf("%d",num_words);
}
return (EXIT_SUCCESS);
}
感謝您的幫助。我只是一個初學者。如果我想在存儲到數組之前將單詞的所有字母轉換爲小寫,該怎麼辦? (int i = 0; i = 65 && story [j] <= 90) story [j] + = 32;} } @david –
2015-04-05 14:28:19
將'#include'作爲頭文件,然後更改'strncpy((char *)story [i],p,strlen(p));'將所有字符轉換爲較低值。我會更新這個例子。你已經做出了正確的選擇來學習C,沒有其他人提供C做的權力和控制權,但是擁有這樣強大的權力是責任。學習C是一個旅程,而不是一場競賽。旅行愉快。 –
2015-04-05 16:00:41
另外,手動完成時不需要添加'#include'。看看ASCII字符[** ASCII碼 - 擴展ASCII表**](http://www.ascii-code.com/)。請注意,所有小寫字符的值都比「大寫」字符的「32」更大。因此,您只需檢查字符串中的每個字母,如果它是大寫字母,則將「32」添加到它的值以將其更改爲小寫字母。 (在'ctype.h'中也有一個'tolower(char p)'函數,你可以使用任何一種方法('add 32'或者爲你的字符串中的每個字符調用'tolower(ch)') –
2015-04-05 16:10:59