Okay, so it looks like we've got a couple of errors in your program as it is now. Let's take a look!
First thing's first. Notice that you have Semicolons at the end of your if statements.
void lost()
{
if (match=='L'); //NOTE: This is a useless if statement
lose=lose+1; //As is, this line will ALWAYS RUN regardless of what character is pressed.
}
void won()
{
if (match=='W'); //Same as Above ^^^^^
win=win+1;
}
Remember that in C, the if statement will execute the next statement conditionally. Remember also that a ; in C is a statement. So, by adding a semicolon after an if statement, you're nullifying the if conditional because the if statement will run the semicolon conditionally, and not your lose = lose + 1;
.
Consider writing this instead:
void lost()
{
if (match == 'L')
{
lose = lose + 1;
}
}
void won()
{
if (match == 'W')
{
win = win + 1;
}
}
Furthermore, I noticed that you've inserted a break command to avoid an infinite while(1) loop. To avoid this problem. Consider using match = _getch() instead of cin << match.
match = _getch();
In addition, your Ratioo variable is not receiving anything but 0 due to truncation. To get the percentage you're looking for, you must cast your win/total to double as follows:
ratioo = ((double)win / (double)total) * 100;
So, Now we get to detecting the ESC And ENTER Keys! This is exciting. So, in order to read in these invisible characters, you have to understand that to the computer, these keys are just numbers. The ESC Key is number 27, and the ENTER Key is number 13 (Look Up the ASCII Table for a full list). So To detect them you need to do the following:
match = _getch();
if (match == 27) //27 is the ASCII Code for the Escape Key
{
break;
}
OR Just Substitute 13 if you're looking for the Enter key. By adding A while(1) Loop around it, you can pause a program until that key is pressed (AND ignore all other input).
My Final Version of your Code can be viewed below:
#include<iostream>
#include<conio.h>
using namespace std;
int match = 0;
int win = 0;
int lose = 0;
int ratioo = 1;
int total = 0;
void lost()
{
if (match == 'L')
{
lose = lose + 1;
}
}
void won()
{
if (match == 'W')
{
win = win + 1;
}
}
int main() {
cout << "Welcome to winratio calculator!" << endl;
cout << "Pressing W adds one win point" << endl;
cout << "Pressing L adds one lose point" << endl;
cout << "Press ENTER to start" << endl;
cout << "Press ESC to close" << endl;
while (1)
{
match = _getch();
if (match == 13) //13 is the ASCII Code for the Enter Key
{
break;
}
}
while (1)
{
cout << "Last game score: ";
match = _getch();
if (match == 27) //27 is the ASCII Code for the Escape Key
{
break;
}
total++;
won();
lost();
ratioo = ((double)win / (double)total) * 100;
cout << "Games won: " << win << endl;
cout << "Games lost: " << lose << endl;
cout << "Ratio: " << ratioo << "%" << endl;
}
return 0;
}
Enjoy! And I wish you well towards learning C!