0
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() 
{
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    char ch;
    char s[100];
    char sen[100];
    scanf("%c", &ch);
    scanf("%s", s);
    scanf("%[^\n]%*c", sen);
    printf("%c\n", ch);
    printf("%s\n", s);
    printf("%s\n", sen);  
    return 0;
}

//input

  • C
  • Language
  • Welcome To C!!

i didn't get the output for the last printf. what could be the wrong here?

  • 1
    What output _did_ you get? When analysing such problems, it's useful to print quotation marks or other delimiters around your strings, e.g. `printf("s: '%s'\n", s)`, so that you can detect what exactly the input was. Your problem here is that you mix various `scanf` formats that treat white-space and new-lines differently. As a rule, `scanf` is not a good way to read interactive, line-wise input. – M Oehm Mar 23 '23 at 05:49
  • 1
    Change `"%[^\n]%*c"` to `" %[^\n]%*c"` (notice the SP) and you should be fine... – Fe2O3 Mar 23 '23 at 05:58
  • 1
    @Fe2O3 Suggesting `" %[^\n]%*c"` has a weakness like suggesting [`gets()`](https://stackoverflow.com/q/1694036/2410359). Both risk buffer overflow. – chux - Reinstate Monica Mar 23 '23 at 15:27

1 Answers1

1

Input is

"C\n", "Language\n", "Welcome To C!!\n".

scanf("%c", &ch); reads "C". "\nLanguage\nWelcome To C!!\n" remains. "%c" reads/saves 1 character.

scanf("%s", s); reads "\nLanguage". "\nWelcome To C!!\n" remains. "%s" reads/discards leading white-space and reads/saves unlimited non-white-space characters, then appends a null character to s.

scanf("%[^\n]%*c", sen); reads nothing. "\nWelcome To C!!\n" remains. "%[^\n]%*c" stops immediately because the first available character is a '\n' and that is not in the scanset [^\n]. sen unchanged.

what is the problem with last printf

printf("%s\n", sen); attempts to print from the unassigned sen array leading to undefined behavior (UB).


what could be the wrong here?

Failure to check the return value of scanf() in 3 places

With if (scanf("%[^\n]%*c", sen) != 1) puts("Error");, It would become clear, nothing was read.

Using "%s" and "%[^\n]" without a width

scanf("%s", s); risks input overflow. Use a width like scanf("%99s", s); with char s[100];


Could also change code to consume leading white-space.

// scanf("%[^\n]%*c", sen);
//         v---- Note space.
if (scanf(" %99[^\n]%*c", sen) != 1) {
  puts("Error");
}

Even better, stop using scanf() and use fgets() for all user input. Read into a string and then parse.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256