Hello, everyone! I got really confused with the boolean results I got in my lines of code below, which states that 0||0 = 1. In my code, I have z = a||b, all of them are bool variables.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <complex>
#include <ctime>
#include <fstream>
#include <vector>
usingnamespace std;
int main()
{
ifstream List("Names and Scores.txt");
string name;
int score;
vector<string>names;
vector<int>scores;
int score_by_user;
int i;
while(List >> name >> score)
{
names.push_back(name);
scores.push_back(score);
}
cout << "Please enter the score, and I will show you the people with this score." << endl;
cout << "Type Ctrl+Z to quit." << endl;
while(cin >> score_by_user)
{
bool a = false;
bool b = false;
for(i = 0; i < scores.size();i++)
{ try{
if(score_by_user == scores[i])
{
throw 123;
}else{ b = false;}
}catch(...){
a = true;
cout << names[i] << endl;
}
}
cout << a << endl;
cout << b << endl;
cout << z << endl;
bool z = a||b;
if(z == false)
{
cout << "Sorry. The score: " << score_by_user << " is not found." << endl << "Please try another score." << endl;
}
}
}
And the "Names and Scores.txt" is as follows:
1 2 3 4 5 6
Ziyue 123
Hiroko 321
Daniel 321
John 234
Joe 21
Jaja 32
The purpose of the program is to have the user to type a score (such as 321), then the program would output the corresponding names that have the indicated score(Hiroko and Daniel for 321). If there is no such score, the program would say "Sorry, the score XXX is not found. Please type another score." Could you help me investigate what is wrong with my boolean variables? Thank you very much!
Hello Mathes and Athar, thank you SOOO much for your replies! I edited my code above, put the a = true command in the catch brackets, and initialized b = false. But the "z = a|| b" logic still does not work right (I tried to input 321, and a = 1, b = 0, but z = a || b = 0 !!?!!?!) Could you help me? Thank you!!
Programs are executed line-by-line, from top to bottom in C++.
1 2 3
bool a = false;
bool b = false;
bool z = a||b;
a||b is false, which is then assigned to z.
a||b doesn't create some sort of function that calculates a||b anew whenever you use z, it evaluates to either true or false.
Also, you should give your variables proper names - a, b, z are absolutely meaningless and only serve to obfuscate your code. And you can simply use break instead of throwing an exception.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
bool found = false;
for (size_t i = 0; i < scores.size();i++)
{
if (score_by_user == scores[i])
{
found = true;
break;
}
}
if (!found)
{
cout << "Sorry. The score: " << score_by_user << " is not found." << endl << "Please try another score." << endl;
}