Getch(); to terminate, or continue loop

I'm having problems with ending the loop/program. What is it that I'm doing wrong that it just keeps looping no matter what I type in?

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
40
41
42
43
44
45
46
47
48
49
50
51
52
//inches_conversion.cpp


#include <iostream.h>
#include <conio.h>
#include <iomanip.h>

           
   int main()
           
   
   {
   
      int inches, cm; //inches & centimeters
      char type, ans; //type of conversion & answer to continue/stop
      ans='y';
   
      while (ans=='y')
      {
         cout<<"\nType C to convert to Centimeters or I to convert to Inches: ";
         cin>>type;
      
         if (type=='c' | type=='C')
         {
            cout<<"\nEnter the number of inches to be coverted: ";
            cin>>inches;
            cout<<"\n"<<inches<<" inches converts to: "<< (inches*2.54)<<" centimeters.";
         }
         else if (type=='i' | type== 'I')
         {
            cout<<"\nEnter the number of centimeters to be converted: ";
            cin>>cm;
            cout<<"\n"<<cm<<" centimeters converts to: "<< (cm/1)<<" inches."<<endl;
         }
      
         getch();
         cout<<"\n\nDo you want to make another conversion? (y/n): ";
         cin>>ans;
      
         if (ans=='y' | 'Y')
         {
            (ans='y');
         }
         else if (ans=='n' | 'N')
         {
            cout<<endl;
         }
      }
   
      return 0;
   
   }


These lines of code are what I'm specifically having problems & speaking about:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  getch();
         cout<<"\n\nDo you want to make another conversion? (y/n): ";
         cin>>ans;
      
         if (ans=='y' | 'Y')
         {
            (ans='y');
         }
         else if (ans=='n' | 'N')
         {
            (ans='n');
            cout<<endl;
         }
      }
   
      return 0;
   
   }
Last edited on
First of all, it should be
1
2
3
#include <iostream> // No .h
//#include <conio.h> // Outdated, don't use it (so no getch(), clrscr(), whatever)
#include <iomanip> // No .h 

Now, as for the actual logic in your code, it should be
1
2
3
4
5
6
7
8
9
if (ans == 'y' || ans == 'Y')
{
    ans = 'y';
}
else if (ans == 'n' || ans == 'N')
{
    ans = 'n';
    cout << endl;
}

Alternatively, you can just do this:
1
2
3
4
5
6
ans = tolower(ans); // Requires #include <cctype>
//if (ans == 'y') // Nothing to do here, I guess?
if (ans == 'n')
{
    cout << endl;
}
Topic archived. No new replies allowed.