这是获取用户输入用C的最好方法? [英] Which is the best way to get input from user in C?

查看:127
本文介绍了这是获取用户输入用C的最好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多人都说 scanf函数不应该在更严重的节目一起使用,同样与函数getline

Many people said that scanf shouldn't be used in "more serious program", same as with getline.

我就开始丢失:如果我碰到人得了每个输入功能,说我不应该使用其中任何一个,那么我应该怎么用?是否有一个更标准的方式来获得输入,我是不知道的?

I started to be lost: if every input function I got across people said that I shouldn't use any of them, then what should I use? Is there is a more "standard" way to get input that I'm not aware of?

推荐答案

一般来说,与fgets()被认为是一个不错的选择。它读取整行到缓冲区,并从那里你可以做你的需要。如果你想要像行为scanf()的,你可以通过你陪读琴弦的sscanf()

Generally, fgets() is considered a good option. It reads whole lines into a buffer, and from there you can do what you need. If you want behavior like scanf(), you can pass the strings you read along to sscanf().

这样做的主要优点是,如果字符串未能转换,很容易恢复,而用 scanf()的留给你输入的标准输入您需要排出。另外,你也不会在面向混合线路输入与 scanf()的,这会导致头痛的事情时,像 \\ n <的陷阱风/ code>被甩在标准输入常用领先的新codeRS相信输入电话已被完全忽略。

The main advantage of this, is that if the string fails to convert, it's easy to recover, whereas with scanf() you're left with input on stdin which you need to drain. Plus, you won't wind up in the pitfall of mixing line-oriented input with scanf(), which causes headaches when things like \n get left on stdin commonly leading new coders to believe the input calls had been ignored altogether.

这样的事情可能是根据自己的喜好:

Something like this might be to your liking:

char line[256];
int i;
if (fgets(line, sizeof(line), stdin)) {
    if (1 == sscanf(line, "%d", &i)) {
        /* i can be safely used */
    }
}

在上面,你应该注意的是与fgets()收益 NULL 在EOF或错误,这就是为什么我把它包在如果。在的sscanf()调用返回已成功转换的字段数。

Above you should note that fgets() returns NULL on EOF or error, which is why I wrapped it in an if. The sscanf() call returns the number of fields that were successfully converted.

请即与fgets()可能无法读取一整行,如果该行是比你的缓冲,这在严重的程序肯定是你应该更大考虑一下。

Keep in mind that fgets() may not read a whole line if the line is larger than your buffer, which in a "serious" program is certainly something you should consider.

这篇关于这是获取用户输入用C的最好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆