kauajuno
kauajuno

Reputation: 45

Problems doing a while loop

So, recently a user commented a question I did here telling me that calling main() inside the main() function isn't recommended and isn't even valid in c++, and he told me that a better form of approach would be to wrap all of my code in a while(true) loop and to break out, or continue if necessary.

I tried to apply it on a code that I created, but I think I didn't understand what I should do, because I got a problem.

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

int main(){

    float a, b, c;
    char d = 'r';

    printf("Hello!\n");

    while(d == 'r'){

    printf("Enter the first side of your triangle: ");
    scanf("%f", &a);
    printf("\n Now, the second one: ");
    scanf("%f", &b);
    printf("\n Now, the third and last one: ");
    scanf("%f", &c);

    if(a > (b+c) || b > (a+c) || c > (a+b)){
        printf("Impossible! This can't be a triangle!");

    }

    if(a == b && a == c){
        printf("\nYou've got a 3 equal sides triangle!\n");
    }
    else{
        if((a == b && a != c) || (b == c && b != a) || (c == a && c !=b)){
            printf("\nYou've got a 2 equal sides triangle!\n");
        }
        else{
            printf("\nYou've got a 3 different sides triangle!\n");
        }

    }


    repeat();


    }

    system("pause");

}

int repeat(){
    char d;
    printf("Do you wanna repeat?\nPress 'r' if you want, press any other key to quit: ");
    scanf(" %c", &d);
}

No matter if the user presses 'r' or any other key, the loop always happens

Did I do something wrong?

Upvotes: 0

Views: 63

Answers (1)

Yksisarvinen
Yksisarvinen

Reputation: 22219

d in repeat() function has nothing in common with d in main(). They are two different, unrelated variables. So when you change one of them, the other doesn't change at all.

You can either return that variable:

int main()
{
    char d = 'r';
    ...
    while (d == 'r')
    {
        ...
        d = repeat();
    }
}

char repeat()
{
    char d;
    printf("Do you wanna repeat?\nPress 'r' if you want, press any other key to quit: ");
    scanf(" %c", &d);
    return d;
}

Or use output argument:

int main()
{
    char d = 'r';
    ...
    while (d == 'r')
    {
        ...
        repeat(&d);
    }
}

void repeat(char* d)
{
    printf("Do you wanna repeat?\nPress 'r' if you want, press any other key to quit: ");
    scanf(" %c", d);
}

Upvotes: 2

Related Questions