我有一個函式可以回傳陣列中的行數、字符數和單詞數。出于某種原因,當我回圈遍歷陣列以列印值時,我只得到了正確的行值,字符和單詞回傳為 0。所有函式都是由我的教授預先確定的,我的作業是填寫它們。
int main(int argc, char **argv)
{
int *myArray = get_counts(argv[1]);
for (int i = 0; i < 3; i )
{
printf("%d\n", myArray[i]);
}
return 0;
}
int *get_counts(char *filename)
{
FILE *file;
file = fopen(filename, "r");
if (file == NULL)
{
printf("NULL FILE");
}
char c;
int h;
bool whitespace = true;
static int arr[3] = {0,0,0};
do
{
c = fgetc(file);
if (c == '\n')
{
arr[0] ;
}
}while (c != EOF);
while (true)
{
h = fgetc(file);
if (feof(file))
{
break;
}
else if (ferror(file))
{
printf("error reading file");
}
arr[2] ;
if (whitespace && !isspace(h))
{
arr[1] ;
whitespace = false;
}
else if (!whitespace &&isspace(h))
{
whitespace = true;
}
}
fclose(file);
return arr;
}
uj5u.com熱心網友回復:
最好的選擇可能是在一個回圈中迭代檔案(您也可以rewind()在第一個回圈之后)。使用的回傳值fgetc()來確定您的位置,EOF而不是單獨feof()呼叫。我還將結果陣列設為(輸出)引數,而不是使用靜態變數(如果您想從多個執行緒呼叫它,則后者不可重入,而且很容易做到):
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
void get_counts(char *filename, int arr[3]) {
memset(arr, 0, 3 * sizeof(int));
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("NULL FILE");
return;
}
bool whitespace = true;
for(;;) {
int c = fgetc(file);
if(c == EOF)
break;
else if(c == '\n')
arr[0] ;
else if (whitespace && !isspace(c)) {
arr[1] ;
whitespace = false;
} else if (!whitespace && isspace(c))
whitespace = true;
arr[2] ;
}
fclose(file);
}
int main(int argc, char **argv) {
int myArray[3];
get_counts(argv[1], myArray);
for (int i = 0; i < 3; i ) {
printf("%d\n", myArray[i]);
}
}
上述檔案的輸出為:
39
94
715
字數 94 不同意,wc -w但您可以使用不同的單詞定義。
將計算和 i/o 分開是個好主意,因此請考慮打開和關閉檔案main()并傳入檔案句柄。例如,stdin如果您不想使用物理檔案,則使用檔案句柄代替它變得很容易。
uj5u.com熱心網友回復:
在第一個 do-while 回圈之后,條件 EOF 發生。
do
{
c = fgetc(file);
if (c == '\n')
{
arr[0] ;
}
}while (c != EOF);
所以下面的while回圈沒有效果。
您應該只使用一個回圈來計算行數、單詞和字符。
請注意,變數c應宣告為具有型別int
int c;
如果檔案未打開,您還需要退出該功能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513298.html
上一篇:從字典物件中獲取多個陣列
下一篇:如何獲取C中指標指向的值的地址?
