简体   繁体   中英

How do I modify this program to count the number of characters that aren't spaces?

For my assignment I need to modify the following program. I can not use strings.h.

int main(void)
{
 int c, countSpaces = 0;

printf("Type sentence:\n");

do
{
  c = getchar();     
  if (c == ' ')
    countSpaces = countSpaces + 1;
}
while (c != '\n');     

printf("Sentence contains %d Spaces.\n", countSpaces);

return 0;
}

I tried using

if (c != EOF)
    countSpaces = countSpaces + 1;
}
while (c != '\n');     

printf("Sentence contains %d Spaces.\n", countSpaces - 1);

but that seems like a hacky and unelegant way to do this. Can anyone help and/or explain to me how to do this better?

Thanks in advance

The code I posted counts the spaces in a sentence, I want to modify it to count all the characters in the input sentence. – fbN 21 secs ago

Have another counter outside the if condition.

#include <stdio.h>

int main(void)
{
    int c;
    int countSpaces = 0;
    int countChars = 0;

    puts("Type sentence:");

    do {
        c = getchar();
        countChars += 1;
        if (c == ' ') {
            countSpaces += 1;
        }
    } while (c != '\n');     

    printf("Sentence contains %d spaces and %d characters.\n", countSpaces, countChars);

    return 0;
}

Two notes. foo += 1 is shorthand for foo = foo + 1 without the precendence complexities of foo++ .

Blockless if or while is playing with fire. Eventually you'll accidentally write this.

if( condition )
    do something
    whoops this is not in the condition but it sure looks like it is!

Always use the block form.


$ ./test
Type sentence:
foo bar baz
Sentence contains 2 spaces and 12 characters.

Note this says 12 because it's including the newline. That's because it's checking what c is after it's already been counted. You can fix this by checking c as its read. This is a fairly normal "read and check" C loop idiom.

// Note, the parenthesis around `c = getchar()` are important.
while( (c = getchar()) != '\n' ) {
    countChars++;
    if (c == ' ') {
        countSpaces++;
    }
}
$ ./test
Type sentence:
foo bar baz
Sentence contains 2 spaces and 11 characters.

I make this code that count length of the string given It's like strlen function. and I used just scanf and it works perfectly even with spaces.

#include <stdio.h>

int main()
{
    char *str = calloc(sizeof(char),50);
    int i = 0, count = 0;

    printf("Type sentence:\n");
    scanf("%[^\n]",str);

    while (str[i++] != '\0')
        count++;                    //length of the string 

    printf("%d",count);
    return 0;
}

and if you want just to count the characters in the string given use this code below:

#include <stdio.h>

int main()
{
    char *str = calloc(sizeof(char),50);
    int count = 0;

    printf("Type sentence:\n");
    scanf("%[^\n]",str);

    for (int i = 0; str[i] != '\0'; i++)
        if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z'))
            count++;


    printf("Sentence contains %d characters.\n",count);
    return 0;
} 

the output :

Type sentence:                                                                                                             
hello world                                                                                                                
Sentence contains 10 characters.       

I always prefer to use fgets() when reading a line from the console ( stdin ):

#include <stdio.h>

int main(void)
{
    int i;
    int length = 0;
    char buffer[1024];

    printf( "Enter some text> " );
    fgets( buffer, sizeof(buffer), stdin );

    // If the user inputs > 1024 letters, buffer will not be \n terminated
    for ( i=0; buffer[i] != '\n' && buffer[i] != '\0'; i++ )
    {
        length += 1;
    }

    printf( "length: %d\n", length );

    return 0;
}

you can just calculate the result like this

int main(void)
{
    int c, countSpaces = 0;

    printf("Type sentence:\n");

    do
    {
        c = getchar();
        if (c == ' ')
        countSpaces++;
    }
    while (c != '\n');

    int countChar = c - countSpaces - 1 ; // -1 new line

    printf("Sentence contains %d Spaces.\n", countSpaces);
    printf("Sentence contains %d chars.\n", countChar);

    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