开发者

Handling error from gets_s() gracefully?

My code uses gets_s() to get a string input from the user.If the user enters a string whose l开发者_运维问答ength is greater than the specified in gets_s, the application aborts.So how to handle that gracefully?

Thanks.


1) gets_s is not a Standard function: apparently it is provided as an extra by Microsoft compilers

2) use fgets, remove the trailing '\n' if needed and if there is no trailing '\n' deal with extra long input

Example

size_t len;
char buf[1000];
if (fgets(buf, sizeof buf, stdin)) {
    buflen = strlen(buf);
    if (len) {
        if (buf[len - 1] == '\n') {
            buf[--len] = '\0'; /* adjust len and remove trailing newline */
        } else {
            /* something bad hapenned */
            if (len == sizeof buf - 1) {
                /* possibly large input */
            } else {
                /* small input */
            }
        }
    } else {
        /* no characters read at all, this is a strange occurrance */
    }
} else {
    /* fgets returned NULL: EOF on stdin? or maybe some error? */
}


you can invoke _set_invalid_parameter_handler at the beginning of your program to set a callback function to handle the error, in the callback function, you should check the value of errno.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜