简体   繁体   中英

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:

#include<stdio.h>

main()
{
       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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM