0

Sorry I'm sure how to word my question properly.

I'm working on an assignment and I'd like to add a feature to the error checking. I have a scanf that asks for a word (which is only 5 characters long max). If the user inputs a string that is 6 characters long like candle, it will only copy over candl.

Here is my take on it. Though I'm sure this isn't the most efficient way to do it.

printf("\n\tEnter word: ");
scanf("%s", input);
if (strlen(input) > MAX_LETTERS){
    int i = 0;
    while (i < MAX_LETTERS){
        word[i] = input[i];
        i++;
    }
    printf("the word is %s", word);
}

Basically checks to see if the input is greater than the max amount of letters allowed. And then if it is, it loops and then only copies over the max amount of letters. Any help would be very much appreciated. Thank you in advance!

user1730056
  • 623
  • 3
  • 11
  • 19

1 Answers1

2
scanf("%ns", input);

Where n= number of characters to be read.If in your case it is 5 then have

scanf("%5s", input);

To avoid buffer overflow using scanf() you can specify the number of characters to be read as shown above. Assuming this is what you wanted .

I would always suggest using fgets() while reading strings

fgets(input,sizeof(input),stdin);

You can specify how many characters you want in the second parameter.

PS: fgets() comes with a newline character

Gopi
  • 19,784
  • 4
  • 24
  • 36