Yes No Loop

Having an issue when user types more than one letter in my do while loop.
It repeats "Would you like to make another calculation? (Y/N): " multiple times.
How do I limit this? I have tried setw() but that didn't seem to change anything.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
char response;

 do{
  
    //CODE HERE 


 cout << "Would you like to make another calculation? (Y/N): ";
 cin >> response

    do{
    if(toupper(response)!= 'Y' && toupper(response) != 'N'){
        cout << "Please enter 'Y' or 'N'." << endl;
        cout << "Would you like to make another calculation? (Y/N): ";
        cin >> response;}
    }while(toupper(response) != 'Y' && toupper(response) != 'N');


 }while(toupper(response) == 'Y');
Last edited on
add std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); after each input operation. Do not forget to #include <limits>
You didn't give the full code, but i tried to understand what you were trying to do. I think my code is helpfull.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

#include<iostream>

using namespace std;

int main()
{
    char ans;
    int num1;
    int num2;

    cout<<"Welcome to calculator"<<endl;
    number_get: //creates a label named number_get
    cout<<"Write 2 numbers to find their sum, difference, product, quotient"<<endl;
    cin>>num1>>num2;

    cout<<"Sum:"<<num1+num2<<endl;
    cout<<"Difference:"<<num1-num2<<endl;
    cout<<"Product:"<<num1*num2<<endl;
    cout<<"Quotient"<<num1/num2<<endl;

    cout<<"Do you want to continue with the calculator 'Y' or 'N'"<<endl;
    ans_get:
    cin>>ans;

    if (ans=='Y' || ans=='y') // || means "OR"
    {
        goto number_get; //Goes to label number_get
    }
    else if (ans=='N' || ans=='n')
    {
        return 0; // returns 0 thus closing the program
    }
    else
    {
        cout<<"Invalid answer, please write again"<<endl;
        goto ans_get;
    }
}

More for goto at :http://www.tutorialspoint.com/cplusplus/cpp_goto_statement.htm
I posted this already on a different thread where you pointed someone to a goto tutorial, but everything I've been taught recommends against using goto statements.
Topic archived. No new replies allowed.