0

I am trying to input a string in C and print it. My sample code is given below:

#include<stdio.h>
main()
{
    char a[5];
    scanf("%[^\n]a",a);
    printf("%s",a);

}

The problem is, I have initially assumed the string length as 5. But if I take a string with length more than 5, it works correctly. Why is this happening? Shouldn't the permitted string length be less than 5?

8
  • "Why is this happening?" Undefined behaviour is undefined. "Shouldn't the permitted string length be" Permitted by whom? You pass to scanf() (implicitly) the address of a's 1st element. You need to explicitly tell it how much it may scan. Commented Jul 22, 2017 at 9:24
  • when I declare char a[5], what does this 5 actually mean? @alk Commented Jul 22, 2017 at 9:27
  • 1
    Also a scans a float. To scan a "string" use s. If you have defined a char[5] that allows a possible "string" of length 5-1=4. C needs 1 char to store "string's" 0-terminator. To tell scanf() to only scan 4 chars use %4s. Commented Jul 22, 2017 at 9:30
  • Have you posted the original code here? what is %a in scanf? Commented Jul 22, 2017 at 9:33
  • 3
    main() - implicit int has been an error since C99. Commented Jul 22, 2017 at 9:39

1 Answer 1

2

Why is this happening?

"Undefined behaviour is undefined."

Shouldn't the permitted string length be less than 5?

Permitted by whom? You pass to scanf() (implicitly) the address of a's 1st element. You need to explicitly tell it how much it may scan.

Also a scans a float. To scan a "string" use s.

If you have defined a char[5] that allows a possible "string" of length 5-1=4. C needs 1 char to store the "string's" 0-terminator.

To tell scanf() to only scan 4 chars use %4s.

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

6 Comments

The square brackets shouldn't be followed by s, they are a conversion specifier on their own. The a here is taken as a literal character which will fail matching.
Perhaps scanf("%4[^\n]",a); is required. Note %s skips spaces. Also worth mention to check the return value from scanf
Even better idea: Never use scanf.
Ey, guys please feel free to edit my answer as you feel is made sense, I already regret to have answered to a scanf-issue... :{
@army007 For user input? fgets, because you always want to read a complete line (you can convert it as needed afterwards, e.g. with strtol or sscanf).
|

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.