2

I am trying to read 2 lines of user's input. For the first sequence, if I type in nothing and just hit return key, the program the prints enter the second sequence but not allowing the second scanf. Basically the return just terminates both scanf, resulting in both str1 and str2 empty.

printf("enter the first sequence: ");
scanf("%[^\n]%*c", str1);

printf("enter the second sequence: ");
scanf("%[^\n]%*c", str2);

Is there any way that I can fix this?

Acorn
  • 24,970
  • 5
  • 40
  • 69
rodan
  • 57
  • 3

1 Answers1

3

The format specifier for strings is %s, so just use this instead:

printf("enter the first sequence: ");
scanf("\n%s", str1);

printf("enter the second sequence: ");
scanf("\n%s", str2);

As @AjayBrahmakshatriya commented: \n matches any number of \n characters.

The problem with %c when reading char with scanf is that it treats the newline as input, as I explained in this example.


However, if I were you, I'd just use fgets(), like this:

fgets(str1, sizeof(str1), stdin);
fgets(str2, sizeof(str2), stdin);

If you go with this approach, you will then probably be interested in Removing trailing newline character from fgets() input?

gsamaras
  • 71,951
  • 46
  • 188
  • 305