0

I've got this program:

#include <stdio.h>

void countCharacter(char str[], char *p, int Count)
{
    p=str;
    while(*p!='\0')
    {
        Count++;
        p++;
    }

    printf("The string, %s, has %d characters", str, Count-1);
}

int main()
{
    char str[100];
    char *p;
    int Count = 0;

    printf("Enter any string:  \n");
    scanf("%c", str);
    fgets(str, 100, stdin);
    
    countCharacter(str, p, Count);
    return 0;
}

*For this particular exercise I was not allowed to use the sizeof operator or strlen() function *

The code is supposed to count the number of characters in an array and give that as the output. For example, if I were to input test I should get the following output:

Enter any string:  
test
The string, test, has 4 characters.

However, I end up with this instead:

Enter any string:  
 test
The string test
 has 4 characters

Any help on why this is would be greatly appreciated.

  • I'm gussing the string you are imputting (and you could verify this with a debugger) includes a newline. E.g., when you type in `test`, C stores it as `test\n`. Later, when you print it, the newline also gets printed. – cocomac Oct 13 '21 at 02:21
  • Does this answer your question? [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input) – Adrian Mole Oct 14 '21 at 13:16
  • Yeah it did! Thank you for the input it was very helpful – TonsilStone Oct 14 '21 at 19:15

1 Answers1

0

From C11 standard regarding fgets:

The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

Based on this, the fgets includes the new-line character \n. You could correct the code by removing the line feed character. For example: str[strlen(str) - 1] = ‘\0’;.

Another thing worth noting is that line scanf("%c", str); writes the first character entered to the array, which is immediately discarded by fgets. So for the test case discussed in the question, I get the result:

Enter any string:
test
The string, est
, has 3 characters

Also, variable p in main() is never initialized in the program and is immediately discarded inside of countCharacter(). I'm not sure of the intent, but it seems that it would make sense to move the variable definition char *p; from inside of main() to inside of countCharacter() and get rid of parameter p of countCharacter().

Jonathon S.
  • 1,928
  • 1
  • 12
  • 18