KKKKK
KKKKK

Reputation: 13

How to use "scanf" to input specific letter?

from my knowledge in high school.

scanf("%[^A-Z]s", input);

it is mean input can be any characters but except capital letter.

but in case of i want to receive input only character [A-F] how can i do it?

in my sense it should be written like this:

scanf("%[A-Z]s", input);

It looks like you use regex but anyway it was't work

So, when i run it

$./a.out 
asdfasdfABC 
`[]@

[] is some alien character but i can not type.

Upvotes: 1

Views: 7857

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409442

The problem is, most likely, that you do not check for errors, and print the string even when the scanf call fails.

With the pattern "%[A-Z]" you only scan for uppercase letters, and if the string you input doesn't begin with upper case letters scan will fail. This of course means that the string input will never be filled, and will contain random data which you then print.

I recommend you read e.g. this reference. It will tell you that the function will return the number of items successfully scanned, which should be 1 in your case. If the scanf function in your code doesn't return 1 then there is a problem.

So you need to do something like

if (scanf(...) == 1)
    printf(...);
else
    printf("Something went wrong when reading input\n");

Upvotes: 1

Shashi K Kalia
Shashi K Kalia

Reputation: 743

In this case you can simply write code as

    scanf("%[A-F]s", input);

now input would carry only from A to F.

Upvotes: 1

Related Questions