1

I am new to C programming and i cant understand why can't I take a string input as the cursor is skipping taking input like in scanner class in java. Please help. It's Compiling successfully but while execution the input line is getting skipped. I'm attaching my code here:

#include<stdio.h>
#include<string.h>
int main()
{
    int n;

char ch[1000];
int end=0;
while(1)
{
 printf("1. Reading a string\n"
     "2. Display the string\n"
     "3. Merge two strings\n"
     "4. Copy n characters from mth position\n"
     "5. Calculate the length\n"
     "6. Count the no. of words, lines and characters\n"
     "7. Replace with 'hello'.\n"
     "Any other number to exit\n");
    scanf("%d", &n);   
switch(n){
case 1:
{
    printf("Enter the string\n");
gets(ch);//have already tried fgets and scanf also but no luck. 
break;
}
...
Wolf
  • 9,679
  • 7
  • 62
  • 108
  • Also be aware of [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – kaylum May 31 '22 at 07:40
  • What my edit is about: subsequent string literals are combined to one string by the compiler – Wolf May 31 '22 at 07:41
  • The issue `'\n'` is left in the input buffer after `scanf("%d", &n);` is executed. you need to clear it before reading the string. Your gets() reads left-over '\n' and considers it as valid input, thus your program doesn't stop for your input. Another note gets() shouldn't be used you can use `scanf("%999[^\n]", ch);` To clear input buffer read this https://stackoverflow.com/a/7898516/3496596 – Mysterious Jack May 31 '22 at 07:55

0 Answers0