0

So I need to write a function which counts the frequency of a character in a string in C. The function parameters must be just the character I want to count. So here's my code:

#include <stdio.h>
#include <string.h>

int charFrequency(char c) {
    char str[500];
    int i, nr = 0;
    printf("Enter the string: ");
    fgets(str, sizeof(str), stdin);
    for(i=0; i < strlen(str); ++i) {
        if (str[i] == c) {
            nr++;
        }
    }
    return nr;
}


int main(void) {
    char c;
    int nr;
    printf("Enter the character you want to count: ");
    c = getc(stdin);
    getc(stdin); // what is the role of this code line? if I delete this line the programs does not work anymore.
    nr = charFrequency(c);
    printf("The frequency is %d", nr);
    return 0;
}

I have a problem when I read the character I want to count. I use getc but the program doesn't work fine. But if I write again getc(stdin) the program works fine.

I also tried with scanf but I have the same issue. Can someone explain me how getc works?

Yonlif
  • 1,770
  • 1
  • 13
  • 31
DaniVaja
  • 211
  • 1
  • 7
  • 4
    You type 'F', 'ENTER', 'THE STRING', 'ENTER'... your `getc()` deals with the 'F', your second `getc()` deals with the 'ENTER' and the `fgets()` inside the function deals with 'THE STRING' and the last 'ENTER'; if you omit the 2nd `getc()`, the `fgets()` deals with the 'ENTER' after the 'F' – pmg Jul 18 '20 at 19:20
  • 2
    Similar to: [fgets doesn't work after scanf](https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf), and [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). It is best not to mix your input methods. You can get the character to match by using `fgets()` and taking the input string's first character. – Weather Vane Jul 18 '20 at 19:23
  • the function: `getc()` returns an `int`, not a `char` – user3629249 Jul 18 '20 at 22:02
  • 2
    the second call to `getc()` is to consume the trailing '\n' – user3629249 Jul 18 '20 at 22:03
  • OT: regarding; `for(i=0; i – user3629249 Jul 18 '20 at 22:08
  • what happens if the user enters a EOF or only a '\n' for either of those inputs? Therefore, the code should be checking the result of the first call to `getc()` and the result of `fgets()` – user3629249 Jul 18 '20 at 22:11
  • _Side note:_ Don't put `strlen` in the condition expression in a `for` loop. It slows down the running time from O(n) to O(n^2) (e.g.) if length of the string was 1000, instead of scanning the string _once_ for a total of 1000 bytes fetched, it will scan the string 1000 times--1000*1000 bytes. Or, 1,000,000 bytes will be fetched. Do this: `size_t len = strlen(str); for (i=0; i – Craig Estey Jul 18 '20 at 22:24
  • Or, better yet, do: `for (int t = *str++; t != 0; t = *str++) { if (t == c) nr++; }` – Craig Estey Jul 18 '20 at 22:27

0 Answers0