0

I'm having a problem with this program I don't understand the scanf("%[^\n]s",s);, because I don't understand what went wrong, the problem shown in the execution goes through the other scanef but when it gets to this one scanf("%[^\n]s",s);, skip and show the result. Where is the error?

another the program statement asks to use gets or getline but I couldn't use it.

scanf("%d", &numberInteger);
scanf("%f", &numberDouble);
scanf("%[^\n]s",s);

code:

int main() {
    int i = 4;
    double d = 4.0;
    char s[] = "HackerRank ";
    int numberInteger = 0;
    float numberDouble = 0.0;
    char ttt;

    scanf("%d", &numberInteger);
    scanf("%f", &numberDouble);
    scanf("%[^\n]s",s);
  
    //strcat(s, suruba);
  
    printf("%d\n%.1f\n%s", i+numberInteger, numberDouble+d, &s);
    return 0;
}
  • Your `scanf("%[^\n]s",s);` should be `scanf("%[^\n]",s);`. – SGeorgiades Mar 03 '22 at 01:32
  • This is a common mistake. Even though `%[^\n]` reads a string like `%s`, it's not a modifier of `%s`. You don't combine them. – Barmar Mar 03 '22 at 01:33
  • There should also be a space so `scanf(" %[^\n]", s);`. Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). Some explanation: most of the format specifiers for `scanf` automatically filter leading whitespace, but `%c` and `%[]` and `%n` do not. Adding a space in front of the `%` instructs `scanf` to filter leading whitespace here too. It's also has no protection against buffer overflow – Weather Vane Mar 03 '22 at 01:37
  • That's why it skips the line. Also in `printf` the `&` should be removed, and it seems strange that you are recycling such a tiny input buffer. – Weather Vane Mar 03 '22 at 01:41

0 Answers0