user5411115
user5411115

Reputation: 101

Taking a fixed length string as input in C

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?

Upvotes: 0

Views: 2329

Answers (1)

alk
alk

Reputation: 70883

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.

Upvotes: 2

Related Questions