user437038
user437038

Reputation:

Removing contents of variable in C

I want to delete the contents of an int variable when it gets to an else statement.

The program requests a number between 1 and 5 using scanf and the number is stored in the int variable and if the number isn't between 1 and 5 then the user is directed to an else statement and I have used a goto statement to take it back to the start and I was wondering how I removed the contents of the variable during the else statement so I don't create a continuos loop.

With getchar it's fpurge(stdin). I'm running Mac OS X.

BELOW IS THE CODE:

#include <stdio.h>

int main (int argc, const char * argv[])
{
    
    int code;
  
start:   
    
    puts("Please type your error code.");
    puts("Range 1-5: ");
    scanf("%d", &code);
    
    switch(code)
    {
        case 1:
            printf("INFORMATION\n");
        case 2:
            printf("INFORMATION\n");
        case 3:
            printf("INFORMATION\n");
        case 4:
            printf("INFORMATION\n");
        case 5:
            printf("INFORMATION\n");
        default:
            printf("INFORMATION\n");
            goto start;
    }

}

Upvotes: 0

Views: 232

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564741

Just set the int value to something else, eg:

theValue = 0;

Upvotes: 3

Byron Whitlock
Byron Whitlock

Reputation: 53921

You are probably looking for a do...while loop

Edit Don't forget your break statements!!

do
{
    puts("Please type your error code.");
    puts("Range 1-5: ");
    scanf("%d", &code);  

    switch(code)
    {
        case 1:
            printf("INFORMATION\n");
            break;

        case 2:
            printf("INFORMATION\n");
            break;

        case 3:
            printf("INFORMATION\n");
            break;

        case 4:
            printf("INFORMATION\n");
            break;

        case 5:
            printf("INFORMATION\n");
            break;

        default:
            printf("INVALID CODE\n");break;
    }

} while(code<1 || code> 5);

Upvotes: 0

Related Questions