我有一個非常大的文本文件,我試圖對其進行文字分析。在字數統計中,我可能也在尋找其他信息,但爲了簡單起見,我將其留下了。 在這個文本文件中,我有以星號「*」分隔的文本塊。我下面的代碼掃描了文本文件,並按照它應該打印的字符和單詞#,但是我希望在滿足星號後重置計數器,並將所有信息存儲在某種表格中。我並不擔心我如何製作表格,因爲我不確定如何在星號之間爲每個文本塊循環相同的計數代碼。C重置FOR循環中的數據計數器
也許一個for循環像
for (arr = strstr(arr, "*"); arr; arr = strstr(arr + strlen("*"), "*"))
示例文本文件:
=-=-=-=-=-=-=-=-=-=-=-=-=-=-
I have a sentence. I have two sentences now.
*
I have another sentence. And another.
*
I'd like to count the amount of words and characters from the asterisk above this
one until the next asterkisk, not including the count from the last one.
*
...
...
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
(EOF)
Desired output:
*# #words #alphaChar
----------------------------
1 9 34
-----------------------------
2 5 30
-----------------------------
3 28 124
...
...
I have tried
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int characterCount=0;
int counterPosition, wordCount=0, alphaCount=0;
//input file
FILE *file= fopen("test.txt", "r");
if (file== NULL)
printf("Cannot find the file.\n");
//Count total number of characters in file
while (1)
{
counterPosition = fgetc(speechFile);
if (counterPosition == EOF)
break;
++characterCount;
}
rewind(file); // Sends the pointer to the beginning of the file
//Dynamically allocate since array size cant be variable
char *arr= (char*) malloc(totalCharacterCount);
while(fscanf(speechFile, "%c", &arr[i]) != EOF) //Scan until the end of file.
i++; //increment, storing each character in a unique position
for(i = 0; i <characterCount; i++)
{
if(arr[i] == ' ') //count words
wordCount++;
if(isalpha(arr[i])) //count letters only
alphaCount++;
}//end for loop
printf("word count is %d and alpha count is %d", wordCount,alphaCount);
}
wordcount和alphacount未初始化。你也可以在每個空間增加wordcount,所以「」(2個空格)可以算作兩個單詞。和'char * arr =(char *)malloc(totalCharacterCount * sizeof(int));'可以是'char * arr = malloc(totalCharacterCount);' – wildplasser
已添加修正。但這不是問題。我重寫了大部分代碼,而不是複製和粘貼,所以初始化會滑掉我的想法。 – user3465668
當只需要一次傳遞時,爲什麼程序會進行三次傳遞(兩次用於文件,一次用於數組)。另外:該計劃似乎與你的目標幾乎沒有關係。 – wildplasser