james
james

Reputation: 1

understand my logic of my while do if code in c ? 37 lines/spaces of code

The code I am writing is basically a question about asking the user to enter in there first name. If the name is blank, ie, the user forgets to enter in there first name, then the code will mention that the user forgot to enter in there name, and ask again. It should continue to ask until the condition is met.

// This sample compares user input to what is being typed. If the 
// input is void of any charicters before pressing enter, it will print a reply. 

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

int main()
{
    char firstname[25];

    printf("Please enter your first name:");
    fgets(firstname,25,stdin);

    // ask to enter in a name. If no name or text is present,
    // will reply with no name entered
    // and will loop untill a name is pressed and entered

    do
    { 
        printf("You pressed enter before entering your first name.\n Please enter first name");             
    }
    while (firstname == NULL || strcmp(firstname,"")==0);

    if(!strcmp(firstname, "firstname"))
    {
        printf("Thank you %s! for entering in your first name",firstname);
    }

    getchar();
}

It only loops once. So, not sure why it will not continue and also, break the loop to say "thank you %s! Can anyone give a different example so it does work and I can understand it better?

Upvotes: 0

Views: 166

Answers (3)

blindauer
blindauer

Reputation: 394

As mentioned by Blagovest Buyukliev you need to move your fgets into the loop. But also, fgets will include the return character in the string (see here), so the call to compare it against "" won't work like you expect.

You could compare it against "\n". Or use gets, which doesn't include the newline.

Also, there's really no reason to check firstname against NULL, it's a stack variable, and will never be NULL. And, at the end your printf will only execute if someone's firstname is literally "firstname", since that's what you're comparing.

Upvotes: 0

Anon.
Anon.

Reputation: 60053

Not quite the problem you're encountering, but it's one you'll encounter soon:

if(!strcmp(firstname, "firstname")) 

strcmp returns 0 if the strings are equal, and returns a positive or negative value if they are different.

This means that if you try and interpret the result as a boolean, strcmp returns true when the strings are different, and false when they are the same.

Can you see the problem on the quoted line now?

Upvotes: 0

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43558

In the do...while loop you only have a single printf statement that doesn't change the condition of the loop. Consider moving the line fgets(firstname,25,stdin) inside the loop.

Upvotes: 1

Related Questions