C-language: quick n00b question

  • Thread starter Thread starter kheiron1729
  • Start date Start date
Click For Summary
SUMMARY

The forum discussion centers on a C programming issue related to character input handling. The user encounters problems with their code when trying to read a character after reading a string. The suggested solution involves replacing the second getchar() and scanf() combination with a single getchar() to correctly capture the character input without discarding it. This adjustment resolves the input issue, allowing the program to function as intended.

PREREQUISITES
  • Understanding of C programming syntax and structure
  • Familiarity with memory allocation using malloc
  • Knowledge of input/output functions such as printf and scanf
  • Basic understanding of string manipulation in C
NEXT STEPS
  • Research proper usage of getchar() in C for character input
  • Learn about memory management and error handling in C with malloc
  • Explore string functions in C, particularly fgets() and strlen()
  • Study debugging techniques for C programs to identify input/output issues
USEFUL FOR

Beginner C programmers, students learning about input handling, and developers troubleshooting character input issues in their C applications.

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 ·
Replies
3
Views
2K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 1 ·
Replies
1
Views
11K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 19 ·
Replies
19
Views
3K