C-language: quick n00b question

  • Thread starter Thread starter kheiron1729
  • Start date Start date
AI Thread Summary
The discussion centers on a C programming issue where a user is trying to read a string and count occurrences of a specified character. The problem arises from the use of both getchar() and scanf() for reading input, which may lead to unexpected behavior. It is suggested that replacing the second getchar() with a direct assignment of getchar() to the character variable could resolve the issue. The importance of clear problem descriptions in programming queries is also emphasized. The thread highlights common pitfalls in handling input in C.
kheiron1729
Messages
5
Reaction score
0
Code:
int main() {
    int n;
    char ch;
    char* str;
    int i;
    printf("Enter the number of values you want to enter in your string: ");
    scanf("%d", &n);
    str = (char*)malloc(sizeof(char)*n);
    printf("Enter the string: ");
    getchar();
    fgets(str, n, stdin);
    printf("%s",str);
    printf("Now enter the character you want to check for: ");
    getchar();
    scanf("%c", &ch);
    printf("ok cool");
    printf("The character '%c' occurs %d times", ch, count_char(str,ch));
    return 0;
}

why is not working. I don't have much time and I am going to start with next problem. Can anyone who is adept at C help me with thing. Pretty please
 
Physics news on Phys.org
Please be more specific than "is not working." A description of what your program is doing that it shouldn't be doing would be helpful.

You might be having a problem with these lines:
Code:
printf("Now enter the character you want to check for: ");
getchar();
scanf("%c", &ch);

Why do you have both getchar() and scanf()? getchar() might be picking up the character that is entered, but it is discarding the character. Something like
ch = getchar();

without the scanf() after it might fix things.
 

Similar threads

Replies
3
Views
1K
Replies
1
Views
10K
Replies
3
Views
1K
Replies
12
Views
2K
Replies
12
Views
2K
Replies
7
Views
2K
Replies
1
Views
2K
Back
Top