Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C ignore dashes on scanf

I’m trying to load in two values from a string separated by " – ".
I can’t figure out what to put in the scanf to ignore this dash.

Here’s a simplified snippet that illustrates the problem:

char first[3];
char second[3];

char* str = "foo - bar";
sscanf(str, "%s <what should be here> %s", first, second);

printf("%s %s", first, second);

If nothing is placed in the placeholder the program prints "foo -"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To tell scanf to expect a -, put a - in the format string:

sscanf(str, "%s - %s", first, second);

Also, make your arrays big enough to hold the characters you expect plus a terminating null character:

char first[4];
char second[4];

You should also limit scanf to the size of the receiving arrays:

sscanf(str, "%3s - %3s", first, second);

If the - might not be present, you need additional code to handle that; a simple scanf is insufficient. Similarly, if the strings might be longer than three characters, you need additional code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading