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
351 views
in Technique[技术] by (71.8m points)

c - Read no more than size of string with scanf()

Edit: 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).


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);
}

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?

question from:https://stackoverflow.com/questions/12306591/read-no-more-than-size-of-string-with-scanf

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

1 Reply

0 votes
by (71.8m points)

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);

ensures that scanf reads no more than 3 characters.


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

Just Browsing Browsing

[3] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...