Home > Software engineering >  Variable resets after getting another variable input
Variable resets after getting another variable input

Time:10-25

I wrote a simple code of a ballot box, it should only start voting if the amount of voters is higher or equal 31. But, when I insert any value starting with 0, like 04, it changes voters to 0.

I need to use values like this as input because it's specified in question. 04 for a president, 08 for another one and 00 for none.

Also, I'm using president as string because I read that numbers starting with 0 are readen as octal.

What can I do to voters amount never change when inputting a value in president?

int main() {
    int option, voters = 0, i = 0;
    char president[2];
    setlocale(LC_ALL,"");

    do {
        printf("Options\n1 - Insert amount of voters\n2 - Start voting\n3 - Leave\nChoose: ");
        scanf("%i", &option);

        while (option <= 0 || option >= 4) {
            printf("This option doesn't exist, try again: ");
            scanf("%i", &option);
        }

        switch (option) {
          case 1:
            system("cls");
            printf("Amount of voters: ");
            scanf("%i", &voters);
            break;
          case 2:
            system("cls");
            if (voters <= 30) {
                printf("There isn't enough voters. Returning to main menu...");
                break;
            } else {
                for (i = 1; i <= voters; i  ) {
                    printf("Insert president vote: ");
                    scanf("%s", president);
                }
            }
            break;
        }

    } while (option != 4);
    return 0;
}

CodePudding user response:

The problem is in scanf("%s", president); because you defined president as char president[2]; which means president holds only two characters.

Why this is a problem?

Well because scanf adds a null character at the end automatically when getting a string from the console which means when you input 04, scanf will store "0\0" into president.

How to fix that?

Just extend the char president[2]; to be char president[3];

  •  Tags:  
  • c
  • Related