Program not entering right loop?

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
{
        char choice;
	cout << " Enter w to write or r if you want to read from the file: ";
	cin >> choice;
	
	
	if(choice == 'W'| 'w')
	{
		int x;
		cout << "How many numbers would you like to add? ";
		cin >> x;

			for(int i=0; i < x; i++)
			{
				double text;
				cout << "Enter number to add: ";
				cin >> text;
				myfile << text << endl;	
			}
		myfile.close();
		return 0;
	}

	else if (choice == 'R' | 'r')
		{
		  string line;
		  ifstream myfile (filename.c_str());
		  if (myfile.is_open())
		  {
		    while ( myfile.good() )
		    {
		      getline (myfile,line);
		      cout << line << endl;
		    }
		    myfile.close();
  		}

		return 0;
		}
}


So when I compile and run my program I give the user the option to enter w or r to read or write from a text file. But no matter what letter I enter it always enters the loop that allows the user to write to the file. What am I doing wrong?
Last edited on
" | " is the wrong operator for logical OR. It is actually known as the bitwise OR.
Use " || ".

1
2
3
if(choice == 'W' || choice == 'w')
//Note that I had to write out each condition.
// choice == 'W' || 'w' does not work as you might think. 


Alternatively, you can convert the letter to lowercase or uppercase, so you don't have to worry about the case.

1
2
3
4
5
6
7
8
9
10
#include <cctype>

//...

char choice('\0');
cin >> choice;
to_lower(choice);

if(choice == 'w')
//... 


Edit:
A third choice since you are working with a menu and chars is the switch-case.
1
2
3
4
5
switch(choice){
    case 'w': //Blah...
        break;
//...
}
Last edited on
Thanks daleth. That completely solved my problem.
Topic archived. No new replies allowed.