Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 990
MrHappyAsthma Avatar asked Sep 06 '12 18:09

MrHappyAsthma


People also ask

What is the use of scanf %3s STR );?

"ensures that scanf reads no more than 3 characters." --> Not quite. "%3s" will first read an unlimited number of leading white-space characters. Then it will read and save up to 3 non-white-space characters.

How do I get the length of a scanf string?

You can use assignment-suppression (character * ) and %n which will store the number of characters consumed into an int value: int count; scanf( "%*s%n", &count ); printf( "string length: %d\n", count );

What is the problem with scanf () to read a string?

Explanation: The problem with the above code is scanf() reads an integer and leaves a newline character in the buffer. So fgets() only reads newline and the string “test” is ignored by the program. 2) The similar problem occurs when scanf() is used in a loop.


2 Answers

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.

like image 99
Daniel Fischer Avatar answered Oct 02 '22 23:10

Daniel Fischer


the safest way is to use

fgets(string, 4, stdin); 

here you can store maximum 3 characters including one space reserved for NULL ('\0') character.

like image 21
Timothy Malche Avatar answered Oct 02 '22 22:10

Timothy Malche