开发者

fscanf C - determining letter instead number

I am loading matrix from file and here comes the question, how to treat if开发者_StackOverflow there will be fault in loading file if there will be letter instead of number? I am especially asking - how to determine, that I loaded letter?

Thx


If the input read by fscanf() does not match the expected type (as determined by the conversion specifier), this will be reported by the return value of fscanf() (which is equal to the number of coversion specifiers successfully read).

int x;   
if ( fscanf( file, "%d", &x ) != 1 )
{
    // input was not a number
}

More generally speaking, the whole scanf() family of functions is primarily aimed at reading whitespace-separated, trivial data. Usually it is more easy and reliable to read in a complete line (using fgets()), and then doing the parsing internally. (strtol() and strtod() can be of help here, but strtok() should be used with care, especially in a multithreaded environment.)


Don't fscanf().

fgets() and sscanf().

In case of error, you still have the original data for error recovery (or to show the user, or whatever)

And always check the return value of the scanf family of functions.

if (fscanf(stdin, "%d", &var) != 1) { /* oops */ }

if (fgets(buf, sizeof buf, stdin) == NULL) { /* oops */ }
if (sscanf(buf, "%d", &var) != 1) { /* oops */ }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜