Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit scanf function in C to print error when input is too long?

I want to limit the scanf function so when I enter for example a char* array <String...> that has more then 30 characters, it will not get it and my output will be error.

I got a hint to use [^n] or something like that but I don't understand how to do it? I know that I can use scanf("%30s"..) but I don't want the input to be valid and just the error.

Any help would be great.

like image 625
user1386966 Avatar asked Dec 03 '22 03:12

user1386966


2 Answers

If you must use scanf then I believe that the best that you can do is use the width specifier with something like: "%31s", as you've already mentioned, then use strlen to check the length of the input, and discard the string and report an error if the input is longer than your limit.

Or possibly skip the strlen by additionally using an %n in your format string, e.g. "%31s%n".

A format string using something like %[^\n] in place of %s simply instructs the function to continue reading until a newline, consuming other whitespace characters along the way. This is useful if you want to allow the input to include whitespace characters.

Review the docs for scanf (here's a copy of the man page).

like image 158
pb2q Avatar answered Feb 06 '23 03:02

pb2q


You could use fgets and sscanf. With fgets you can read a little bit more than 30 characters and then check that you didn't get more than 30 characters.

Or if you really want to use scanf use it with something more than 30 like %32s.

like image 22
ouah Avatar answered Feb 06 '23 03:02

ouah