Making my code robust in c

Guys can please help find a way on how to make my code robust. I am only allowed to accept string inputs. If I like input numbers, it would display an invalid input. Instead of continuing on the output.

This code is about getting five-string inputs and it displays the longest word.

Example output:

5stringsLong

Here is the code:

#include <stdio.h>
#include <string.h>

int main() {
    
   int wordSize[5], longestInt;
   char longest[50];
   char words[5][50];
   char longestWord[50];
   
   printf("\n");

   for(int i=0; i < sizeof(words)/ sizeof(words[0]); i++) {
        printf("Enter string %d: ", i+1);
        gets(words[i]);

        wordSize[i] = strlen(words[i]);
    }
    
    longestInt = wordSize[0];

    for(int i=0; i < sizeof(words)/ sizeof(words[0]); i++) {
        
        if(longestInt < strlen(words[i])) {
             longestInt = wordSize[i];
        } 

    }

    if(longestInt == wordSize[0]) {
       strcpy(longestWord, words[0]);
    } else if(longestInt == wordSize[1]) {
      strcpy(longestWord, words[1]);
    } else if(longestInt == wordSize[2]) {
      strcpy(longestWord, words[2]);
    } else if(longestInt == wordSize[3]) {
      strcpy(longestWord, words[3]);
    } else if(longestInt == wordSize[4]) {
      strcpy(longestWord, words[4]);
    } else {
      printf("Invalid");
    }
    

    printf("The longest word is: %s", longestWord);

    
   printf("\n");
 
    return 0;
}

I think a do-while-loop (or however feet-controlled-loops are done in C) is the way to go.
Basically a loop that takes in an input, checks if the input violates your condition. If it does, keep the loop going.
You nest that into the for-loop of your inputs.

can I like do something like this?

do {

“something”

}while(*the last character of words[i] == ‘\0’ *)

and I will place it inside the first for loop.

If you can do it depends if C supports this kind of loop and how exactly it is written ^^°
Like, I do know there’s also a “repeat-until” loop, so you gotta look which of those are in C.

That said, yeah that the idea ^^

1 Like

I don’t think your loop is the biggest issue here. What if the input isn’t five lines of strings? What if it is 4? Or 6? Or 10?

2 Likes

C has do-while. They aren’t my favorite, but you can use them.

1 Like

@bbsmooth I think I designed my code to only accept five inputs only, but that’s a good point.