How to compare and check in c++ using loops and array - c++

Here is my new edited code I am having trouble with my final if loop for the X and O's stored inside an array. I am trying to check if there is an X or O already inside the array or not. If there is one it asks the user for another input then start over again however when i run the program this happens:
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
Please Enter Box Number: 1
player X your number is 1
X | 2 | 3
4 | 5 | 6
7 | 8 | 9
Please Enter Box Number: 1
Please enter another Number2
player O your number is 1
O | 2 | 3
4 | 5 | 6
7 | 8 | 9
Please Enter Box Number:
char c;
cout << "Please Enter Box Number: ";
cin >> c;
if (c > '9' || c < '0')
{
// error message
cout << "please enter a number 1-9" << " ";
cin >> c;
cin.ignore(numeric_limits<int>::max(), '\n');
}
if (c < '9' || c > '0')
{
int number = c - '0';
if (board[number - 1] == 'X' || board[number - 1] == 'O')
{
cout << "Please enter another Number";
cin >> c;
cin.ignore(numeric_limits<int>::max(), '\n');
}
else if (board[number -1] != 'X' || board[number - 1] != 'O' ) {
if (player == 'X')
{
player = 'O';
}
else
{
player = 'X';
}
cout << "player " << player << " your number is " << number << endl;
// Your implementation here...
board[number - 1] = player;
}
}
}

First the second question (the easy one):
Return exits from the current function. So, after the return, no further instruction in your function is executed. You should remove the return and put the rest of the code (that should not be executed if the input is not valid) in the else block of that if.
First question:
Why do you check that the index of each position in the array (as in board[7] = '8'). You already know the position, what you need to mark in each cell is the player who uses it; for example set values of 'X' (player 1), 'O' (player 2), ' ' (empty).
Instead of nine "if", it will be easier if you convert your input 'c' into an integer and use it as an index. With ASCII characters (I do not know if this still workds with WCHAR, UTF-8 and so on) you could make it quick and dirt:
int k = c - '0';
board[k] = player;
Edit:
Taking into account checking that the square is not already used:
int k = c - '0';
if (board[k] == ' ') {
board[k] = player;
} else {
cout << "This square is already used";
}

To loop back until a valid value has been entered, you can do something like this:
int number = 10;
while( ( number > 9 ) || ( number < 0 ) )
{
std::cout << "Please Enter Box Number: ";
std::cin >> number;
}
std::cout << "Your number is " << number << std::endl;
I am not too sure what you are asking about the other part. I will edit my response if/when I do.

http://www.asciitable.com/
if you look at the ascii chart, you will notice that all of the characters have a decimal value to them. So when your teacher subtracts '0' from what the user entered, say '1' he is really doing:
int number = (int)'1' - (int)'0'; // x will equal 1
your array can then be accessed directly using [ ] notation so:
board[number] = player

Related

weird braces/bracket symbol at the end of my output. (my program is on printing out the next alphabet).

#include <iostream>
using namespace std;
int main()
{
char input, letter1,letter2;
cout << "Enter a letter: ";
cin >> input;
if ( (input >= 'A' && input >= 'Z') || (input <= 'a' && input <= 'z') )
{
if ( (input >= 'A' && input >= 'X') || (input <= 'a' && input <= 'x') )
{
letter1 = input + 1;
letter2 = input + 2;
cout << "Your letter trio today is " << input << letter1 << letter2<<".\n";
}
else if ( input == 'Y' || input == 'y' )
{
letter1 = input + 1;
cout << "Your letter trio today is " << input << letter1 <<".\n";
}
else
{
cout << "Your letter trio today is " << input <<".\n";
}
}
}
if I input y, my output becomes yz{. If I input Y, my output becomes YZ[. If I input Z, my output becomes Z[. Any ideas? thanks guys
Welcome to the ASCII representation of characters! C++ standard only requires that representation of digits are contiguous, but most common implementation use ASCII. The ASCII code for Y is 0x59. 0x59+1 is 0x5A the ASCII code of Z. And just guess what is the character with ASCII code 0x5B? Yes it is [ so your output is normal...
The same, ascii code of lower case y is 0x79, and ascii code of { is 0x7B

Program that finds Highest, Lowest, and Average of 5 number from an Array

My homework is to write a program that finds the highest, lowest, and average of 5 numbers in an Array that the user inputs. Here is my problem, the user does not have to enter all 5 numbers. But has to enter at least 2 numbers minimum.
I have the whole program done already I am having a problem with the beginning, below is my code where I am having a problem:
// Ask for name and explain program
cout << "Please enter your name: ";
cin >> name;
cout << endl;
cout << "Hi " << name << ", please enter up to 5 whole numbers." << endl;
cout << "I will find the HIGHEST, LOWEST, and AVERAGE number." << endl;
// Loop through users input
for (int i = 0; i < SIZE; i++)
{
cout << "Enter number " << (i + 1) << " : ";
cin >> number[i];
// Validate that the user has entered atleast 2 numbers
if (i >= 1 && i < 4)
{
cout << "Do you wish to enter another number (Y/N)? : ";
cin >> continue_game;
// Validate that the user only enters Y/N
while (continue_game != 'Y' && continue_game != 'y' && continue_game != 'N' && continue_game != 'n')
{
cout << "Please type in (Y/N): ";
cin >> continue_game;
}
// What happens if user chooses NO
if (continue_game == 'N' || continue_game == 'n')
{
i = 5;
}
// What happens if user chooses YES
else if (continue_game == 'Y' || continue_game == 'y')
{
i = i;
}
}
}
PROBLEM: If the user presses no after the 2nd number the remaining elements get a number asigned to them like : -8251616. Is there any way to make sure that the elements get assigned a zero or stay blank please help its due tomorrow and I can not figure it out.
SIZE = 5
Don't set i = 5 when the user says no. Just end the loop with a break; statement.
Also, the i = i; statement in the yes case is useless.
When you're getting the highest, lowest, and average values, make sure you only look at the values from 0 to i-1, so you don't access the uninitialized elemends of the array.
If you really want zeros you need to fill array with zeros:
int number[5] = {};
or
int number[5];
for (int i = 0; i < 5; ++i) {
number[i] = 0;
}
However this will give wrong output if the user enter less than 5 numbers. What you should do is to count how many numbers user entered and then use values from 0 to count - 1.
Advice, use break; instead of i = 5;.

how can i make the loop and change number to string

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int number=0;
cout<<"enter an number to cumpute";
cin>>number;
if(number=0)
cout<<"0"<<endl;
for(number>0;51>number;) {
number--;
cout<<"=";
}
for(number>10;number%10==0;) {
cout<<"|";
}
for(number>5;number%5==0;) {
cout<<"+";
}
cout<<endl;
system("PAUSE");
return 0;
}
(i got textbook called by Y.Daniel Liang. I can not find any thing like this) I have no idea how to make this loop work and I try use "while" and not working either. Should i just cout the "=" "+" "|", or start as string. I hope the output look like this.
BarPlot – A Simple Bar Graph Plotter:
Input a number in range [0 50] or a negative number to terminate:
| Enter Number: 6
| ====+> 6
| Enter Number: 12
| ====+====|=> 12
| Enter Number: 50
| ====+====|====+====|====+====|====+====|====+====> 50
| Enter Number: 53
| ERROR: 53 is not in acceptable range.
| Enter Number: 33
| ====+====|====+====|====+====|==> 33
| Enter Number: 0
| 0
| Enter Number: 5
| ====> 5
| Enter Number: -1
------------------------------------------------
BarPlot – End Plot by User Request
There is no need for you to convert a number to a string in order to solve the problem. The object cout can handle printing both numbers and strings without you needing to cast between them.
//example
int number = 1;
string str = "hello;
char c = '!';
//print hello1!
cout << str << number << c;
Here is a solution to the problem that does not require the need to cast an integer to a string.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
//output inital prompt
cout << "BarPlot – A Simple Bar Graph Plotter:\n";
cout << "Input a number in range [0 50] or a negative number to terminate.\n\n";
//read in input
int number = 0;
cout << "Enter Number: ";
cin >> number;
//continue asking for input until a negative number is given
while (number >= 0){
for (int i = 1; i < number; ++i){
//special symbol every 10th char
if (i % 10 == 0) cout << "|";
//special symbol every 5th char
else if (i % 5 == 0) cout << "+";
//every other char
else cout << "=";
}
//print 0 or the number with an arrow before it
if (number == 0) cout << 0;
else cout << "> " << number << "\n";
//re-ask for input
cout << "\nEnter Number: ";
cin >> number;
}
//output ending message
cout << "BarPlot – End Plot by User Request\n";
return EXIT_SUCCESS;
}

Unique String printing every 5th 10th and last position

Been stumped for a good day now on this one, I know I just need the "=" sign and ">" end piece to the question.Any hints or advice>?
int main()
{
//Calling in Variables
int data;
int counter;
//Step 1:Prompt the user to pass in a positive integer between (0-50)
cout << "Type in a number between 0-50 to plot your bar: " << endl;
cin >> data;
//Step 2: Error check for bad numbers that have been input.
if(data < 0) {
cout<< "ERROR: " << data << " is not in acceptable range."<< endl;
}
//Step 3:
if(data >= 0 && data <= 50){
for(int counter =1; counter <= data; counter++) {
if(counter % 10 !=0)
cout<< "|";
else(data%5 == 0)
cout << "+";
}
}
else
cout << "BarPlot - End Plot by User Request"
return (0);
}
Create a simple Bar Graph Plotter (BarPlot) that takes in a positive integer number between [0 50], and plots the
number as a simple bar. The program should only accept data within this range. Any negative value input should
terminate the Program. Any input larger than 50 should result in an error message and a prompt to enter another
number.
Example Output:
BarPlot – A Simple Bar Graph Plotter:
Input a number in range [0 50] or a negative number to terminate:
| Enter Number: 8
| ====+==> 8
| Enter Number: 15
| ====+====|====> 15
| Enter Number: 50
| ====+====|====+====|====+====|====+====|====+====> 50
| Enter Number: 65
| ERROR: 65 is not in acceptable range.
| Enter Number: 0
| 0
| Enter Number: 1
| > 1
| Enter Number: 5
| ====> 50
| Enter Number: -1
BarPlot – End Plot by User Request
You have a really simple question that you have made complex by putting it in a big lump of text. You have pretty simple logic, you want to print out = except for every 5th and 10th number. You were basiclly already there:
for(int counter =1; counter <= data; counter++) {
if(counter % 10 ==0)
cout<< "|";
else if(counter%5 == 0)
cout << "+";
else
cout << "=";
}
cout << ">" << yournumberthing << endl;
You just needed to think about it some more.

.exe has stopped working

I'm pretty new to programming, and this program runs, but when I am able to enter the batting record, the console is presented with a Windows error ".exe has stopped working...". This has never happened before, and as a new programmer, I think it's scary.
#include <iostream>
using namespace std;
//Prototype to keep console from closing.
class KeepRunning {
public:
~KeepRunning() {
system("pause");}};
//Define batting values
#define H 1
#define h 1
#define O 1
#define o 1
#define W 0
#define w 0
#define S 0
#define s 0
#define P 0
#define p 0
int main ()
{
KeepRunning kr;
int player; //Assign player number
double sum; //Assign variable for sum of H, h and O, o
double sumHits; //Assign variable for sum of only H and h
double average; //Assign variable for average of H and O
char size[100]; //Allows compiler to view user input as array
int b; //Assign variable for integer size
int letters = 0; //Assing value of 0 to allow compiler to count
cout << "\t\t\tBatting Average Calculator\t\t";
cout << "\n\nEnter the player's number: ";
cin >> player;
cout << "Enter the player's batting record: ";
cin >> size;
bool invalid = false;
while(!invalid)
{
invalid = true;
if ((size[b] == 'H') || (size[b] == 'h')
|| (size[b] == 'O') || (size[b] == 'o')
|| (size[b] == 'W') || (size[b] == 'w')
|| (size[b] == 'S') || (size[b] == 's')
|| (size[b] == 'P') || (size[b] == 'p'))
{
continue;
}
else {
cout << "\nAcceptable batting record codes are: 'H','O','W','S','P'.
Please try again.\n";
invalid = false;
}
}
//Summate H, h, O, o
sum = H + h + O + o;
//Summate
sumHits = H + h;
//Calculate batting average
average = sumHits/sum;
cout << "\nPlayer " << player << "'s batting record: " << size << endl;
cout << "Player " << player << "'s batting average: " << average << endl;
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
Okay, so I've made a couple of changes thanks to yall. But, I've got new problems. First, when I run the program and write a valid input, i.e. "HOWHHHOOWHSPP", nothing happens. The console just stays open displaying the prompts and inputs. Second, when I write an invalid input, i.e. "HOWQQQTTSHH" or anything not including the specific set of letters, the console closes immediately rather than displaying my error message. How can I have the console not only stay open, but redirect the program to start over for any invalid input?
Here's the new code:
#include <iostream>
using namespace std;
//Prototype to keep console from closing.
class KeepRunning {
public:
~KeepRunning() {
cin.get();}};
//Define batting values
#define H 1
#define h 1
#define O 1
#define o 1
#define W 0
#define w 0
#define S 0
#define s 0
#define P 0
#define p 0
int main ()
{
KeepRunning kr;
int player; //Assign player number
double sum; //Assign variable for sum of H, h and O, o
double sumHits; //Assign variable for sum of only H and h
double average; //Assign variable for average of H and O
char size[100]; //Allows compiler to view user input as array
int b=0; //Assign variable for integer size
int letters = 0; //Assing value of 0 to allow compiler to count
cout << "\t\t\tBatting Average Calculator\t\t";
cout << "\n\nEnter the player's number: ";
cin >> player;
cout << "Enter the player's batting record: ";
cin >> size;
bool invalid = false;
while (!invalid && size[b] != '\0')
{
if (size[b] != 'H' && size[b] != 'h' &&
size[b] != 'O' && size[b] != 'o' &&
size[b] != 'W' && size[b] != 'w' &&
size[b] != 'S' && size[b] != 's' &&
size[b] != 'P' && size[b] != 'p')
{
invalid = true;
}
else {
invalid = false;
}
}
//Summate H, h, O, o
sum = H + h + O + o;
//Summate
sumHits = H + h;
//Calculate batting average
average = sumHits/sum;
cout << "\nPlayer " << player << "'s batting record: " << size << endl;
cout << "Player " << player << "'s batting average: " << average << endl;
return 0;
}
In the lines
cout << "Enter the player's batting record: ";
cin >> size;
I think you should take input to b, not size. In your code b is uninitialized, so it contains garbage value. When you use b as index for size, the index is invalid, which causes your program to crash.
It looks like the problem is that you're attempting to use the variable b as the index to the array before assigning a value to it. I think what you want is a loop to check all of the characters entered by the user, so something like this:
int b = 0;
while (!invalid && size[b] != '\0') {
//stuff in your existing loop
}
'\0' is automatically added to the end of the user input and indicates to the loop that all of the characters entered by the user have been read.
As a side note, it would be good to restructure your loop to check if the input you're checking is invalid and if it is, set invalid to true. There's no reason to use continue here. Something like this would be better:
if (size[b] != 'H' && size[b] != 'h' &&
size[b] != 'O' && size[b] != 'o' &&
....etc.) {
invalid = true;
}
The loop will end as soon as an invalid character is encountered.