Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c++ - How to validate input using scanf

How can I validate the user input by using scanf. Right now I have something like this, but doesn't work.

NOTE: I have the atoi just to validate that the scanf validation works.

scanf("%[0987654321.-]s",buf);

i = atoi(buf);

if(i)
    index = i;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using scanf() is usually a bad idea for user input since failure leaves the FILE pointer at an unknown position. That's because scanf stands for "scan formatted" and there is little more unformatted than user input.

I would suggest using fgets() to get a line in, followed by sscanf() on the string to actually check and process it.

This also allows you to check the string for those characters you desire (either via a loop or with a regular expression), something which the scanf family of functions is not really suited for.

By way of example, using scanf() with a "%d" or "%f" will stop at the first non-number character so won't catch trailing errors like "127hello", which will just give you 127. And using it with a non-bounded %s is just begging for a buffer overflow.

If you really must use the [] format specifier (in scanf or sscanf), I don't think it's meant to be followed by s.

And, for a robust input solution using that advice, see here. Once you have an input line as a string, you can sscanf to your hearts content.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...