问题描述
GCC 4.4.2
gcc 4.4.2
我在读关于scanf函数的文章。我个人从来没有检查一个scanf函数的返回code。
I was reading an article about scanf. I personally have never checked the return code of a scanf.
#include <stdio.h>
int main(void)
{
char buf[64];
if(1 == scanf("%63s", buf))
{
printf("Hello %s\n", buf);
}
else
{
fprintf(stderr, "Input error.\n");
}
return 0;
}
我只是想知道还有什么其他的技术,当他们使用scanf函数时,他们希望得到用户的输入有经验的程序员吗?或者他们使用另一个函数或写自己的?
I am just wondering what other techniques experienced programmers do when they use scanf when they want to get user input? Or do they use another function or write their own?
感谢您的任何建议,
编辑=========
EDIT =========
#include <stdio.h>
int main(void)
{
char input_buf[64] = {0};
char data[64] = {0};
printf("Enter something: ");
while( fgets(input_buf, sizeof(input_buf), stdin) == NULL )
{
/* parse the input entered */
sscanf(input_buf, "%s", data);
}
printf("Input [ %s ]\n", data);
return 0;
}
我想大多数程序员都认为scanf函数是坏的,大多数同意使用与fgets和sscanf。不过,我可以使用与fgets看书来输入。但是,如果我不知道是什么,用户将进入我怎么知道解析什么。例如,如,如果用户是要进入他们的地址,其中将包括数字和字符,并且以任何顺序
I think most programmers agree that scanf is bad, and most agree to use fgets and sscanf. However, I can use fgets to readin the input. However, if I don't know what the user will enter how do I know what to parse. For example, like if the user was to enter their address which would contain numbers and characters and in any order?
推荐答案
不要使用 scanf函数
直接。这是令人惊讶的很难使用。这是更好地读取输入的整条生产线,并再分析它(有可能是的sscanf
)。
Don't use scanf
directly. It's surprisingly hard to use. It's better to read an entire line of input and to then parse it (possibly with sscanf
).
阅读本条目(以及它引用的条目)从comp.lang.c常见问题解答:
Read this entry (and the entries it references) from the comp.lang.c FAQ:http://c-faq.com/stdio/scanfprobs.html
编辑:
好吧,从您自己的编辑解决您的其他问题:如果你允许非结构化的输入,那么你将不得不尝试,直到找到一个工程来分析多种方式的字符串。如果你不能找到有效的匹配,那么你应该拒绝输入,并再次提示用户,可能说明你要输入的是什么格式。
Okay, to address your additional question from your own edit: If you allow unstructured input, then you're going to have to attempt to parse the string in multiple ways until you find one that works. If you can't find a valid match, then you should reject the input and prompt the user again, probably explaining what format you want the input to be in.
对于任何更复杂,你可能会更好使用常规的前pression库,或者是使用专用的词法/语法分析器工具包(例如flex和野牛)。
For anything more complicated, you'd probably be better off using a regular expression library or even using dedicated lexer/parser toolkits (e.g. flex and bison).
这篇关于使用scanf函数接受用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!