user3625236
user3625236

Reputation: 61

Incompatible types in assignment of int to char

void trinti1()
{
    int b,lines;
    char ch[20];

    FILE* file = fopen ("Kordinates.txt", "r");

    while(!feof(file))
    {
        ch = fgetc(file);
        if(ch == '\n')
        {
            lines++;
        }
    }

    fclose(file);
}

Hello guys I am trying to count lines in file, but seems fgetc(file) returns int and it can't be converted to char. Help me what I am doing wrong?

Upvotes: 1

Views: 1929

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40155

void trinti1()
{
    int b,lines=0;
    int ch;

    FILE* file = fopen ("Kordinates.txt", "r");

    while(EOF!=(ch=fgetc(file)))
    {
        if(ch == '\n')
        {
            ++lines;
        }
    }

    fclose(file);
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

In your code ch is not a char, it is char[20] - an array of 20 characters. You cannot assign a result of fgetc to it, because fgetc returns an int (which contains either a single char, or an EOF mark).

Change the declaration of ch to int ch to fix this problem. You can also drop the call to feof because it happens at the wrong time anyway (you call it after read operations, not before read operations).

for (;;) {
    int ch = fgetc(file);
    if (ch == EOF) break;
    if (ch == '\n') lines++;
}

Upvotes: 2

Related Questions