Using strtol to validate integer input in ANSI C

前端 未结 3 2240
梦如初夏
梦如初夏 2021-01-14 07:23

I am new to programming and to C in general and am currently studying it at university. This is for an assignment so I would like to avoid direct answers but are more after

3条回答
  •  梦谈多话
    2021-01-14 08:01

    OP would like to avoid direct answers ....

    validate integer input

    1. Separate I/O from validation - 2 different functions.

    2. I/O: Assume hostile input. (Text, too much text, too little text. I/O errors.) Do you want to consume leading spaces as part of I/O? Do you want to consume leading 0 as part of I/O? (suggest not)

    3. Validate the string (NULL, lead space OK?, digits after a trailing space, too short, too long, under-range, over-range, Is 123.0 an OK integer)

    4. strtol() is your friend to do the heavy conversion lifting. Check how errno should be set and tested afterward. Use the endptr. Should its value be set before. How to test afterward. It consume leading spaces, is that OK? It converts text to a long, but OP wants the nebulous "integer".

    Qapla'

提交回复
热议问题