0

ファイル内のさまざまな文字タイプをカウントすることになっている単純なプログラムに問題があるようです。ファイルがまったく空でない場合でも、常にゼロを出力します。ポインターと関係があると思いますが、間違っている可能性があります。この場合、変数の初期化が必要かどうかも知りたいですか?

// fun.h

void count_char(FILE *f, unsigned *newl, unsigned *let, unsigned *num, unsigned *spec_char);

// main.c

#include <stdio.h>
#include "fun.h"

int main()
{
    unsigned newline = 0, number = 0, letter = 0, special_character = 0;
    char path[256];
    FILE *f_read;
    printf("Insert a file path: ");
    gets(path);
    f_read = fopen(path, "r");
    if(f_read == NULL)
    {
        perror("The following error occurred");
        return 1;
    }
    count_char(f_read, &newline, &number, &letter, &special_character);
    printf("File content:\n\tnewline - %u\n\tletters - %u\n\tnumbers - %u\n\tspecial characters - %u\n", newline, number, letter, special_character);
    return 0;
}

// fun.c

#include <stdio.h>
#include <ctype.h>

void count_char(FILE *f, unsigned *newl, unsigned *let, unsigned *num, unsigned *spec_char)
{
    char c;
    while((c = fgetc(f)) != EOF)
    {
        if(c == '\n')
            *newl++;
        else if(isalpha(c))
            *let++;
        else if(isdigit(c))
            *num++;
        else
            *spec_char++;
    }
    return;
}
4

1 に答える 1

1

このようなことをすると*newl++;: 何が起こるかというと、最初にポインターがインクリメントされ (つまり、次のメモリー位置を指すようにする)、その後、演算子の優先順位に基づいて逆参照されます。

逆参照してからインクリメントしたい場合は、次のように括弧を使用する必要があります。(*newl)++;

于 2013-01-16T20:58:17.487 に答える