Logo Questions Linux Laravel Mysql Ubuntu Git Menu

How to read special characters (punctuation marks, hypens, colons) using scanf function?

I wrote a little piece of code that would input address from the keyboard. However, I am not able to figure out how may I be able to read in special characters, such as hypen, colon etc. Can you please suggest some edit to my code below:


       char address[80];

       printf("Enter address: ");
       scanf("%[a-z | A-Z | 0-9]", address); //How may I include characters like hypen.
       printf("\n\n%s\n\n", address);

Output that I am getting:

Enter Address: Plot No - 16, Palm Grooves, Nagpur - 440022, India

Plot No

No commas, no hyphen, no numeral is being displayed.

Thank you for your help and comments.

like image 569
Niteesh Avatar asked Feb 19 '23 15:02


1 Answers

Add them to the list of acceptable characters one by one, like this:

"%[a-z | A-Z | 0-9/,.-]"

Here is this example on ideone.

Since you are using scanf into a buffer of limited size, it is a good idea to add a size constraint to the format specifier in order to avoid buffer overruns:

char address[81]; // One extra character for padding
printf("Enter address: ");
scanf("%80[a-z | A-Z | 0-9/,.-]", address); // %80 limits the input
printf("\n\n%s\n\n", address);
like image 105
Sergey Kalinichenko Avatar answered Apr 25 '23 03:04

Sergey Kalinichenko