用scanf()读取的字符串大小不超过 [英] Read no more than size of string with 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).
如果我正在阅读用户输入的小项目(例如游戏).可以说我问您想玩吗?
这将接受 yes
或 no
答案.所以我写了一些像这样的简单代码:
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);
}
因此,此代码应仅要求他们输入是
或否
.我将我的 3
.这样,它足以容纳 yes
和 no
.但是,如果有人输入诸如 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?
推荐答案
您的数组必须能够容纳四个
Your array needs to be able to hold four char
s, since it must also contain the 0-terminator. With that fixed, specifying a maximal length in the format,
scanf("%3s", string);
确保 scanf
读取的字符数不超过3个.
ensures that scanf
reads no more than 3 characters.
这篇关于用scanf()读取的字符串大小不超过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!