0

I run the following c program

char str[80] = "String";
printf("hello %s\n", str);
scanf("%s", str);
printf("%s\n", str);
scanf("%[ABCDEF]", str);
printf("hello %s\n", str);

return 0;

For some reason on line 5 when it is suppose to input from Pattern %[ABCDEF], the console simply prints previous string (input from line 3). Why is that so?

5
  • 2
    your str declaration does not make sense. you can't update literal values like that. Commented May 10, 2021 at 17:34
  • 3
    You do know that scanf does return a value - perhaps worth checking Commented May 10, 2021 at 17:57
  • @OldProgrammer i was simply trying to see how the c program is behaving because i'm learing. So yeah, i got the answer from August Karlstorm Commented May 11, 2021 at 11:28
  • @DavidSchwartz if i correct it as scanf(" %[ABCDEF]", str); now string takes only characters specified between [] Commented May 11, 2021 at 11:31
  • @EdHeal Yeah, i realised that just now. Thanks Commented May 11, 2021 at 11:33

1 Answer 1

4

Thats because the first scanf call doesn't read the newline character and the second call to scanf simply reads that newline character. To avoid this start the format string with a space like this:

#include <stdio.h>

int main(void)
{
    char str[80] = "String";

    printf("hello %s\n", str);
    scanf("%s", str);
    printf("%s\n", str);
    scanf(" %[ABCDEF]", str);
    printf("hello %s\n", str);

    return 0;
}

However, you also need to make sure that str doesn't overflow if the user inputs a string longer than 79 characters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.