Search code examples
cfunctionstdio

Character C-function, misconception on its behaviour


An exercise asked to write a function that:

  • reads a sequence of alphabetic characters (without memorizing the sequence) that ends only when the users enters '\n'.

  • returns 1 if the number of capitalized letters went beyond the lower ones of at most an integer m, entered by the user, or 0 else.

I tried with the following code:

#include<stdio.h>

int read(int p,char c)
{
    int M=0,m=0,d;
    char A,Z,a,z;

    while(c != '\n')
    {
        if(A<=c<=Z)
        {
            M++;
        }
        else if(a<=c<=z)
        {
            m++;
        }
        scanf("%c",&c);
    }

    if(M-m>0)
        d=(m-M);
    else 
        d=0;

    if(d==0)
        return 0;
    else if (d<=p)
        return 1;
}

int main()
{
    int a,h;
    char k;

    scanf("%d", &h);
    scanf("%c", &k);
    a=read(h,k);
    printf("%d\n",a);
    return 0;
}

At this point, trying to execute the program with the gcc command, i noticed that the program was taking just the integer, let's say 2, and gave back 0 as if it entered in the function without taking the second scan on the character.

Besides the formal misconception and errors about the program and c function that i'm glad you rectify,

I was trying to understand, because as they say i'm trying to be self-taught, how scanf function and function work in general, when and to who priority is given.

For example in function read it's not clear to me when the value i'm returning to the function are taken putting a higher if as i did.


Solution

  • This isn't going to do what you probably expect

    if(A<=c<=Z)
    

    ... for all sorts of reasons. Firstly, the values of A and Z are uninitialized. Second, the logic is written to be read by a mathematician, not a C compiler.

    You almost certainly wanted this:

    if('A'<=c && c<='Z')
    

    ... and remove the four variables char A,Z,a,z;

    Note that use of character constants such as 'A' and 'Z' assumes a runtime environment using ASCII character sets. If you're interested in a more portable solution, you can look up isupper() and islower()