简体   繁体   中英

formatted input using scanf()

I need to take a string as input, discard eveything that is not a space, hyphen or numbers. In other words I only want positive and negative integer numbers to be read in. I'm not deadset on using scanf but I would prefer it.

What I've tried so far is:

char buffer[200];

scanf("%[0-9 ' ']*%c", buffer); /*this works perfectly, except the hyphen part*/
scanf("%[0-9 - ' ']%*c", buffer); /*no change*/
scanf("%[0-9 '-' ' ']%*c", buffer); /*still no change*/

Obviously only tried one of them at a time.

Grateful for any insight or help you can offer.

I'm surprised this works for you:

scanf("%[0-9 ' ']*%c", buffer);
                 ^--- There's a typo, here. The * should probably be after the %.

Onto more pressing matters... In the C11 standard, at section §7.21.6.2p12, under the [ conversion specifier there are some sentences that explain:

If a - character is in the scanlist and is not the first, nor the second where the first character is a ^, nor the last character, the behavior is implementation-defined.

As a result, I would suggest two things:

  1. You can't rely on 0-9 portably representing the range of characters 0123456789 within your scanset. You're better off explicitly stating 0123456789 .
  2. Your implementation isn't interpreting - as you'd like it to.

I suggest something like this:

assert(scanf("%[- 0123456789]%*c", buffer) == 1);

You need to check the return value. If scanf returns 0, or EOF , then you can't expect anything well-defined by using buffer . I put the - at the start of the scanset, so that it's well defined, and expanded your 0-9 to 0123456789 as mentioned earlier.

I hope that helps :)

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