确保scanf函数只有在一个串读这么多字 [英] ensure Scanf only reads so many characters in a string

查看:126
本文介绍了确保scanf函数只有在一个串读这么多字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我的课我必须使用 scanf函数。因此,建议输入的其他方式是不是我要找的解决方案(如果有涉及scanf函数)

for my class I have to use scanf. So recommending other ways of input is not the solution I am looking for (if there is one that involves scanf)

~~~~~~~

如果我在用户输入正在读一个小项目(例如游戏)。可以说,我问将你喜欢玩?这将接受没有的答案。所以,我写了一些简单的code是这样的:

If I am reading in user input for a small project (for example, a game). Lets say I ask would you like to play? This would accept a yes or no answer. So i write up some simple code like this:

#include <stdio.h>

int main(void)
{
     char string[3]; //The max number of letters for "yes".

     printf("Would you like to play?");
     scanf("%s", string);
}

所以这code应该简单地要求他们输入没有。我设置我的字符数组的大小 3 的长度。这样,它是大到足以容纳没有。但是,如果有人进入无效输入,如 YESSS ,我知道如何将字符串比较事后处理这样的事件,但不会这在技术上/可能覆盖其他地方变量我宣布,因为这会延长我的数组的长度之外?如果是这样,有没有办法来处理这​​个限制3输入的字符或什么?如果不是,为什么/它是如何知道只输入3的大小?

So this code should simply ask them to input yes or no. I am setting the length of my char array to size 3. This way it is large enough to hold yes and also no. But if someone were to enter invalid input such as yesss, I know how to compare the string afterwards to handle such an event, but wouldn't this technically/possibly overwrite other local variables I have declared because it would extend outside the length of my array? If so, is there a way to handle this to restrict 3 input characters or something? And if not, why/how does it know to only input for the size of 3?

*注:我是新来的C和我找不到太多关于这个,所以我AP preciate它,即使这很简单。因为我清楚地失去了一些东西。我来自一个Java的背景,这些都不会,甚至是一个问题。

*Note: I am new to C and I couldn't find much on this so I appreciate it even if this is simple. Because I am clearly missing something. I come from a java background where this wouldn't even be an issue.

推荐答案

您数组需要能够举办四场字符 S,因为它也必须包含0〜终止符。与固定格式指定一个最大长度,

Your array needs to be able to hold four chars, since it must also contain the 0-terminator. With that fixed, specifying a maximal length in the format,

scanf("%3s", string);

确保 scanf函数读不超过3个字符。

这篇关于确保scanf函数只有在一个串读这么多字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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