So I'm working on a Lo Shu Magic Square for my first programming class and I'm stuck. I'm sure everyone here will know what that is but just in case, it's a 2D array that takes 9 numbers from user input, but they have to be between that range (1-9) and also non repeating (where I'm stuck).
I can validate for numbers within the 1-9 range, but I'm having trouble also validating for the second condition of non-repeating numbers
Here's my code for the function that takes user input:
(Oh yea, the 2D array is 3x3 so ROWS = 3 and COLS = 3 and they're being passed to this function)
// Get numbers
void getNumbers(int magicSquare[][COLS], int ROWS)
{
cout << "\nEnter Nine Numbers (1-9)" << endl;
int num;
int n = 0;
for (int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLS; c++)
{
cout << "\tNumber " << (n + 1) << ": ";
cin >> num;
magicSquare[r][c] = num;
n++;
// Input validation
// Validate against numbers outside the range
while (num < 1 || num > 9)
{
cout << "\tError ... Invalid number. Try again" << endl
<< endl;
cout << "\tNumber " << (n) << ": ";
cin >> num;
magicSquare[r][c] = num;
}
// Validate against repeating numbers
while (...) //OMEGA STUCK
{
cout << "\tError ... " << num << " is already in the
Lo Shu Square. Try again" << endl <<endl;
cout << "\tNumber " << (n) << ": ";
cin >> num;
magicSquare[r][c] = num;
}
}
}
cout << endl;
}
I have tried several approaches, from using while loops, to trying temp arrays, and I'm currently attempting to create a new bool function and pass the array and input to it but with little success.
// Validate against repeating numbers
while (repeatNumbers(magicSquare, num)) // Calling boolean function (defined below)
{
cout << "\tError ... " << num << " is already in the Lo Shu Square.
Try again" << endl << endl;
cout << "\tNumber " << (n) << ": ";
cin >> num;
magicSquare[r][c] = num;
}
...
// Validate against repeating numbers function
bool repeatNumbers(int magicSquare[][COLS], int num)
{
bool status;
if (num == magicSquare[COLS][COLS]) //Here I get an error:
{ //"Reading invalid data from
status = true; //'magicSquare[COLS]'.
}
else
{
status = false;
}
return status;
}
Is there a way to ensure that reading a partially filled-in array is well-behaved, what's the best approach? I can't arrive at the correct way, and I just KNOW I'm missing something that is quite logical which my tired brain can't think of at this point.
Any ideas on how to test for both conditions?
Related
i'm having trouble with exercise 9 from chapter 5 of "Bjarne Stroustrup Programming Principles and Practice Using C++".
The chapter is about errors, and the exercise says " Modify the program from excercise 8 to write out an error if the result cannot be represented as an int".
I have tried using various variations of
if (!cin)
error("Input is not an integer");
However the issue I get is that if I read in something that is not an integer it will then either display all the errors or just the "you wanted to sum more values than you entered" error.
This is my full code from excercise 8 before i tried to add the user input error:
#include <iostream>
#include "../../std_lib_facilities.h"
int main()
{
try {
int size = 0;
int numbers = 0;
int sum = 0;
vector<int>values;
cout << "Please enter how many numbers you want to sum\n";
cin >> size;
if (size < 1)
error("you have to enter at least one value!");
cout << "enter some integers and then | to sum them\n";
while (cin >> numbers)
values.push_back(numbers);
if (values.size() < size)
error(" You wanted to sum more values than you entered. ");
cout << "the sum of the first " << size << " numbers ( ";
for (int i = 0; i < size; ++i) {
sum += values[i];
cout << values[i] << " ";
}
cout << ") is : " << sum << "\n";
return 0;
}
catch (exception& e) {
cerr << "Error: " << e.what() << "\n";
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops: Unknown exception!\n";
keep_window_open();
return 2;
}
}
I think that you can use cin.fail() method to detect a wrong input.
for example
int numbers = 0;
cin >> numbers;
if (cin.fail())
{
/* run when the input is not integer. */
}
The loop is not reacting properly when an input outside the parameters is put in. It should only accept 0-9, but I can put any number positive or negative in and it outputs it as is.
I've tried setting the int count to null and 0 on the 4th line, thinking null might allow the while loop which originally said 'while count < 0 or count > 9'. Even at null it skipped the whole loop entirely and didn't allow for any inputs. I set it this way thinking it would loop through as the count is set to 0, but it seems to skip the conditions inside. This is a small function inside a larger lottery program.
void human(int user[], int size) {
const int SIZEOF = 5;
cout << "Enter your 5 lottery number picks.\n";
int count = 0;
while (count == 0) {
if (count >= 0 and count <= 9)
for (count = 0; count < SIZEOF; count++)
{
cout << "Number " << (count + 1) << ": ";
cin >> user[count];
}
else
{
cout << "You must enter 0-9: ";
cin >> user[count];
}
}
}
//EDIT: Here is the code I used based on it being pointed out I was using the //counter
void human(int user[], int size) {
const int SIZEOF = 5;
cout << "Enter your 5 lottery number picks.\n";
for (int count = 0; count < SIZEOF; count++)
{
cout << "Number " << (count + 1) << ": ";
cin >> user[count];
while (user[count] < 0 || user[count] > 9)
{
cout << "You must enter a number between 0 and 9: ";
cin >> user[count];
}
}
}
problems:
your function is missing an output/return value
your outer loop makes no sense
you check count instead of input
you read into a (potentially) out of bounds array
solutions:
use std::vector instead of array
think about input and output of your function
fix input and loops
example:
#include <iostream>
#include <string>
#include <vector>
std::vector<int> lotteryInput(uint32_t count)
{
std::vector<int> numbersPicked;
std::cout << "Enter your " << count << "lottery number picks.\n";
while(numbersPicked.size() < count)
{
int pick;
std::cout << "Number " << numbersPicked.size()+1 << ": ";
std::cin >> pick;
if ((pick >= 0) && (pick <= 9))
{
numbersPicked.push_back(pick);
}
else
{
std::cout << "You must enter 0-9: \n";
}
}
return numbersPicked;
}
int main()
{
auto numbersChosen = lotteryInput(5);
std::cout << "picked numbers: ";
for(const auto& num : numbersChosen)
{
std::cout << num << ", ";
}
}
I'm currently taking C++ and one my assignments is to create a program that checks if the number is a prime number correctly handle the invalid
integer inputs. In addition, user should be able to test as many integers as he or she wants in a single run. In other words, the program should not end unless the user tells you to.
I understand the prime number check part but I cannot figure out to implement the "test as many integers as you want in a single run and handling invalid input"
Any comments and edits to the code would be greatly appreciated. Thank you!
using namespace std;
int main () {
int num, i, count = 0;
cout << "Enter the number to be checked : ";
cin >> num;
if (num == 0)
{
cout << "\n" << num << " is not prime";
exit(1);
}
else {
for(i=2; i < num; i++)
if (num % i == 0)
count++;
}
if (count > 1)
cout << "\n" << num << " is not prime.";
else
cout << "\n" << num << " is prime.";
return 0;
}
Here is the code that you can try. After input the number, the program will ask whether you want to continue or not by inputting y or n.
If the user input y, the program will keep looping and ask the question again otherwise it will break the loop.
Last note : don't use using namespace std (bad habit)
#include <iostream>
#include <string>
int main () {
int num, i, count = 0;
char flag;
while(1)
{
std::cout << "Enter the number to be checked : ";
std::cin >> num;
if (num == 0)
{
std::cout << "\n" << num << " is not prime";
}
else {
for(i=2; i < num; i++)
if (num % i == 0)
count++;
}
if (count > 1)
std::cout << "\n" << num << " is not prime."<<std::endl;
else
std::cout << "\n" << num << " is prime."<<std::endl;
std::cout <<"Do you want to continue? [y/n]";
std::cin >> flag;
if (flag == 'n')
break;
}
return 0;
}
Of course, you can change the y/n to another char or string or int or whatever you want
I need the user input to be saved into my array and then output the array before the user inputs the next time. I have been moving things around different ways but cannot seem to get them to perform properly. I tried to cut down the code to the two functions I am having issues with.
void PlayGame()
{
const int HighestNum = 50;
const int LowestNum = 1;
int RandomNumber = LowestNum + rand() % HighestNum; //set for better random results
cout << "Guess the random number between " << LowestNum << " and " << HighestNum << "!\n\n";
const int attempts = 15;// limits the attempts to guess the random number to 15
int Guess [attempts] = {};
cout << "Enter your guess " << endl;
for (int count = 0; count < attempts; count++)
{
cin >> Guess[count];
int z = RandomNumber, y = Guess[count], r;
r = reviewGuess (z,y);//calling the function that determines the results
switch (r)//switch statement for function results, letting the user know if they matched the number, if the number is higher, or lower
{
case 0:
cout << "You Win!!" << endl;
cout << "\n";
cin.get();
return;
case 1:
cout << "The number is higher than your guess" << endl;
break;
case -1:
cout << "The number is lower than your guess" <<endl;
break;
}
if (count == 15)
{
cout << "Sorry, no guesses remain. The random number was... " << RandomNumber << "!";//so the user can see the random number at the end of their attempts
cout << "\n";
cin.get();
Again();
}
}
return;
}
int DisplayGuess(int member[])
{
for(int i = 0; i < 15; ++i)
cout << "\nGuess " << i + 1 << ": " << member[i];
cout << endl;
return;
}
Try this inside your loop
if(count > 0)
{
for (int j= 0; j < count; j++)
{
cout<<Guess[j];
}
}
Call DisplayGuess() in the first line of the for loop. Since the first you time you call it your array is empty, it shouldn't output anything.
So,
for (int count = 0; count < attempts; count++)
{
DisplayGuess(Guess[count]);
cin >> Guess[count];
int z = RandomNumber, y = Guess[count], r;
r = reviewGuess (z,y);//calling the function that determines the
results
. . . . . .
I am trying to create a program that asks the user for a set of numbers, first asking for the quantity of numbers, then having them input all the numbers. The program then checks the numbers, and determines whether or not the numbers given are in ascending order or not. Then, simply print out "yes ascending" or "no not ascending" and print out the array on one line..So far, my code will just always say that "yes, this is an increasing array!" Please look below for my code. Thanks in advance!..
tested: 1 2 3 4 5 6 --> pass
1 3 5 2 4 6 --> fail (still says it is an ascending array)
#include <iostream>
#include <string>
using namespace std;
bool isAscending(int arr[], int size)
{
for (int i=0; i < size-1; i++)
{
if (arr[i] > arr[i+1])
{
return false;
}
}
return true;
}
int main()
{
int arraysize = 0;
string numbers;
cout << "Enter the size of the array: " << endl;
cin >> arraysize;
if (arraysize < 1)
{
cout << "ERROR: you entered an incorrect value for the array size!" << endl;
}
cout << "Enter the numbers in the array, separated by a space, and press enter: " << endl;
numbers += ' ' + numbers;
cin >> numbers;
int arr[arraysize];
if ( isAscending(arr, arraysize))
{
cout << "This IS an increasing array!" << endl;
}
else
{
cout << "This is NOT an ascending array!" << endl;
}
for (i = 0; i < arraysize - 1; i++)
{
cout << arr[i];
}
return 0;
}
You're reading in "numbers", which you created as type String.
cout << "Enter the numbers in the array, separated by a space, and press enter: " << endl;
numbers += ' ' + numbers;
cin >> numbers;
Your numbers+= line isn't doing anything except adding a space to your numbers string before your cin happens... I know what you're trying to accomplish, and that won't do it.
Then you're suddenly making an array which, without initializing is filled with garbage, and immediately running isAscending on it:
int arr[arraysize];
if ( isAscending(arr, arraysize)){....}
I advise you declare your array before receiving input, read the input line and process it into INTEGERS, and then add each integer to your array. Here is a (crude) correction of the first section of code in your main that just reads in whitespace separated integers and fills the array with them:
int main(){
int arraysize = 0;
int number = 0;
cout << "Enter the size of the array: " << endl;
cin >> arraysize;
if (arraysize < 1) // you should really have this loop until you get correct input
{ cout << "ERROR: you entered an incorrect value for the array size!" << endl; }
int* arr = new int[arraysize];
cout << "Enter the numbers in the array, separated by a space, and press enter: " << endl;
int i = 0;
while(i < arraysize){
cin >> number;
arr[i] = number;
i++;
};
if ( isAscending(arr, arraysize)){ cout << "This IS an increasing array!" << endl; }
else{ cout << "This is NOT an ascending array!" << endl;}
for (int i = 0; i < arraysize; i++){
cout << arr[i];
if( (i+1) == arraysize){ cout << ". ";}
else cout << ", ";
}
return 0;
}
If you're going to whine about somebody giving partial answers that only address the asker's question, maybe you should take the time to write something yourself.