开发者

Removing contents of variable in C

开发者 https://www.devze.com 2023-02-11 08:53 出处:网络
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 nu

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 var开发者_如何学JAVAiable 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;
    }

}


Just set the int value to something else, eg:

theValue = 0;


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消