1
#include <stdio.h>
int main()
{
    char str[100], search[100]; 
    printf("Enter a string ");
    scanf("%[^\n]s",str);
    printf("\n Enter search substring ");
    scanf("%[^\n]s",search);
}

When I run the above code, the first scanf() does execute and takes user input. However, it skips over the second scanf() and ends the program.

I think this happens because the second scanf() finds \n in the buffer (from previous input) and stops. What can I do to correct this behaviour?

  • 4
    `s` should not be a part of the format `%[^\n]`. It is usually `%s` or `%[^\n]`. – Weather Vane Sep 21 '17 at 16:45
  • 1
    Yes ^^ look at that answer. But the big problem with this code is that you will get a buffer overrun if the user enters more than 100 characters. I suggest using fgets() to read the input, rather than scanf. And then `str[strcspn(str, "\n")] = 0;` to strip the newline. – little_birdie Sep 21 '17 at 16:48

0 Answers0