0

I'm currently a beginner in C programming and I'm having doubts about using "goto" to check if the user's string is accepted but I hear a lot of people say "goto" is bad programming.

Currently I'm using "goto" after the "if" check to go back to the "gets" command so the user can type again.

    printf("Full Name: ");
NAME:
    gets(name);
    if (strlen(name) == 0)
    {
        printf("Empty name. Try again: ");
        goto NAME;
    }

Is there a better way to do this other than using "goto" or in this case this is not so bad to use it?

asmp
  • 1
  • 1
  • 1
  • Ya, don't use `goto`. You need a while loop. [See this](https://stackoverflow.com/questions/1754282/how-to-loop-a-console-app) to accomplish your goal. – Nik Oct 28 '17 at 20:35
  • 5
    Don't use `gets`, which is dangerous and obsolete. – Weather Vane Oct 28 '17 at 20:35

2 Answers2

0

Try:

while (strlen(name) == 0) gets(name);

samthegolden
  • 1,366
  • 1
  • 10
  • 26
  • 1
    I think you'll want a `do while` loop. We don't know that `name` contains initialised data before the first iteration. – tangrs Oct 28 '17 at 22:35
0

This is a scheme you can follow:

do
   read input
while input not valid

use input

If you want do display an error message you can do this instead:

read input

while input not valid
   print msg input not valid
   read input

use input

Or this:

while true
   read input
   if input valid
      break
   print input not valid

use input
bolov
  • 72,283
  • 15
  • 145
  • 224