简体   繁体   中英

Counting characters excluding spaces in C using while loop

I'm trying to count the number of characters the user has as an input using a while loop, but for some reason the output counts always one more than the expected value. ( I'm a newbie so please don't hate me for it.)

Here's my code:

#include <stdio.h>
#include <string.h>
int main() {
    int len,i;
    char sttr[29];
    fgets(sttr,29,stdin);
    len = 0;
        i=0;
        while(sttr[i] != '\0'){
        if (sttr[i] != ' '){
            len++;
        }
        i++;

    }
   printf("%d\n",len);

}

The fgets function reads in a line of text and stores that text, including the newline if there's room for it.

So the output is one more because of the newline.

I'm a newbie so

it should be worth mentioning that your while loop finishing is completely relying upon the fact that the null character \\0 is found in sttr[] .

Because you use the function fgets() it will automatically append a \\0 character after the input is stored in sttr[] so it is likely to never be a problem, but...

realize under different circumstances if you were to parse a string like that there is likely to be a much greater chance that the while loop could become an infinite loop because it never found a \\0 character to terminate.

so something like this for example would be more robust:

don't assume a null character will always be present in your string

# include <stdio.h>
# include <string.h>
# define MAX 29

int main ( void )
{
    int len, i;
    char sttr[MAX];

    fgets( sttr, MAX, stdin );

    len = 0;
    i = 0;

    /* make sure i does not index past sttr[MAX] */
    while ( ( sttr[i] != '\0') && ( i < MAX ) )
    {
        if ( sttr[i] != ' ' )
        {
            len++;
        }
        i++;
    }
    printf("%d\n",len);
    return 0;
}

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