Home linux fgets () excess of the length of array of C

fgets () excess of the length of array of C

Author

Date

Category

For example, I have an array

char message [10];

and in it I read from the keyboard line

fgets (Message, 10, Stdin);

The situation can happen when the length of the string entered from the keyboard will exceed the size of the array Message . How to track this excess?


Answer 1

I think something like this:

char message [10];
FGETS (Message, 10, Stdin);
Unsigned Len = Strlen (Message);
If (Message [Len-1]! = '\ n' & amp; & amp;! FeOF (stdin)) Puts ("not fit ...");

Answer 2, Authority 100%

In order not to count the length of the line once again (if it is not required), it is better to establish the penultimate byte buffer at zero before reading and check it. Also in the code shows an example of processing all sorts of exceptional situations.

# Define BUF_SZ 10
// ...
Char Message [BUF_SZ];
Char * RV;
Message [BUF_SZ-2] = 0;
RV = FGETS (Message, BUF_SZ, STDIN);
If (! RV) {
 FPRINTF (STDERR, "FGETS () FAILED. \ N");
} ELSE If (Message [BUF_SZ-2] & amp; & amp; message [buf_sz-2]! = '\ n') {
 FPRINTF (STDERR, "FGETS () Have't Read Full String. \ n");
} ELSE If (FEOF (STDIN)) {
 FPRINTF (STDERR, "FGETS () Encountered An Unterminated String Before EOF. \ n");
} else {
 Printf ("SuccessFully Recieved A String:% S", Message);
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions