Error problem when entering c++ string

Asked 2 years ago, Updated 2 years ago, 23 views

int money(int coin, int add)

{ int coin2;

here:

system("cls");
coin2 = coin;
menu(coin, add);
cout << "Please make a deposit. (Only 100 won units.) :" <<endl;

while (1) {
    cin >> coin;

    if (coin % 100 == 0) {
        coin = coin + coin2;
        goto here;
    }

    else if(coin % 100 > 0){
        cout << "Please deposit in units of 100 won." <<endl;
    }
    else {
        system("cls");
        cin.clear();
        cin.ignore();
        cout << "Enter the correct amount";
        goto guest2;
    }
}
return 0;

}

Originally, when entering a string, I tried to go to else and process it, but when entering a string, the coin value was recognized as zero, so I went to the if statement and repeated errors occur. Advise if there are other ways to handle string exceptions.ㅠ<

c++

2022-09-22 19:01

1 Answers

First of all, coin is a factor that entered as a function in cin >> coin, but it seems very dangerous to use it without declaring a variable.

There is a good way to handle the exception of cin in c++.

// Enter code here
int data;

cin >> data;

if (cin.fail())
{
   cout << "Input Error" << endl;
}
else
{
   cout << "Input Success" << endl;
}

cin.You can check if it fits the int type by checking it at fail().

And this is a difference in individual styles... How about calling a function rather than using a goto statement.

It's a sample code, so please look at it for reference only.

// Enter code here
void display()
{
   ...
   cout << "Please make a deposit. (Only 100 won units.) :" <<endl;
}

int money(int coin, int add)
{
   ...

   display()

   while(1) {
      cin >> coin;

      if (coin % 100 == 0) {
         display();
      }

      ...
   }
}


2022-09-22 19:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.