简体   繁体   中英

How does following statement produce spaces?

What my program "upper" trying to do is making letters upper case. It gets a file from the commmand line as argv; then reads it afterwards it makes them uppercase.

An example: "i wonder if it works" in the example.txt file. In command line:

C:\Users\...>upper example.txt 
I WONDER IF IT WORKS

This was the code I used first:

int main (int argc, char *argv[]){
    FILE * fp;
    int ch;

    if ((fp = fopen (argv[1] , "r+")) == NULL) {
        fprintf (stderr , "Can not be opened.");
        exit(EXIT_FAILURE);
    } 

    while((ch = getc(fp)) != EOF){
        if (isalpha(ch))
            putchar(toupper(ch));
        else                       
            putchar(' ');
    }

    fclose(fp);
    return 0; 
}

It works but I saw a more concise version which doesn't need the else statement.

while((ch = getc(fp)) != EOF){
    putchar(toupper(ch));
}

And it puts the spaces between each word too. How is this possible?

From the documentation

int toupper(int c);

Converts c to its uppercase equivalent if c is a lowercase letter and has an uppercase equivalent. If no such conversion is possible, the value returned is c unchanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM