Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to create some kind of a loop for this code

Tags:

c

loops

I'm new in programming I watched a tutorial for c (about 3 hours long) and I immediately wrote this code. Now everything works fine, but I want to create some kind of loop, i will try to explain what I want as best as I can.

Here is a code I wrote:

#include <stdio.h>
#include <stdlib.h>


int main()
{
    char *characterName;
    char *yes_no;

    characterName = malloc(sizeof(char));
    yes_no = malloc(sizeof(char));

    printf("Enter you name: ");
    scanf("%s", characterName);
    printf("Are you sure[Yes/No]: ");
    scanf("%s", yes_no);

    if(strcmp(yes_no, "Yes") == 0 || strcmp(yes_no, "yes") == 0)
    {
        printf("Your name is %s", characterName);
    }
    else if(strcmp(yes_no, "No") == 0 || strcmp(yes_no, "no") == 0)
    {
        printf("Try again!");
    }
    else
    {
        printf("Unknown command!");
    }

    return 0;
}

What it does is it basically asks you to enter your name and then to confirm it, if you type Yes or yes it will print what your name is, if you type No or no it will print try again, if you enter something else but Yes/yes or No/no it will print unknown command. Now what I want to know is how I can make a loop that will repeat over and over unless I type in yes. Like I entered no or unknown command I want it to ask me to enter my name again. I hope you can understand what I want to do and sorry for my bad English I'm still learning :D.

like image 786
Veljox Marjanovic Avatar asked Jan 30 '26 06:01

Veljox Marjanovic


1 Answers

Like most things in programming, there are many ways to do what you are asking.

One way is to introduce a new variable, called yes_entered or something similar, that will track if the user has entered yes yet. Then inside the if statement where you check if yes was entered you can set this variable to true. To make this into a loop you can put the code you want to repeat inside a while(!yes_entered){ loop.

One other thing, these lines:

characterName = malloc(sizeof(char));
yes_no = malloc(sizeof(char));

are going to cause you problems. You are allocating the two char arrays to be the size of one char. For this case you should probably consider picking a maximum character length and then making these two variables static char arrays. something like:

char characterName[MAX_NAME_LENGTH] ;
char yes_no[MAX_CONF_LENGTH];
like image 80
sgillen Avatar answered Feb 01 '26 20:02

sgillen