Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am writing a program that generates integers and sets the range of the user's choosing.
For example:
Enter the number of integers: 4
Range: 10
4 9 2 1 are generated
Now the user chooses 4 digits at a time until they're correct.
Program will also tell user if they are partially correct.
For example:
User input: 4 9 0 7
Console << 2 of your answers are correct.
I have three files:
Driver.cpp
#include <iostream>
#include "Game.h"
using namespace std;
int main()
{
// Declare variables.
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) {
cout << "Enter the Number of Integers (n): " << endl;
cin >> numberOfIntegers;
cout << "Number of Each Integers from 1 to (m): " << endl;
cin >> rangeOfIntegers;
cout << "Enter your guesses for the " << numberOfIntegers << " integers in the range from 1 to " << rangeOfIntegers << " that have been selected:" << endl;
guess.beginGuessingGame(rangeOfIntegers, numberOfIntegers);
}
if (count == numberOfIntegers) {
cout << "You are correct! Play again? (y/n)";
}
else {
cout << count << " of your guesses are correct." << endl;
}
};
Game.h
// identifiers
#ifndef guessing_game
#define guessing_game
class Guess
{
private :
int * generatedSequence;
int * inputGuess;
int sum;
public :
void generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers);
void beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers);
int getSum() {
return sum;
}
};
#endif
and Game.cpp
#include <iostream>
#include <iomanip>
#include "Game.h"
using namespace std;
void Guess::generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Initialize random number generator.
srand(time(0));
/// Declare array size for the generated sequence to be based on user input.
generatedSequence = new int[inputRangeOfIntegers];
/// Input randomly generated numbers from from 0 to input range into generatedSequence.
for (int i = 0; i < inputNumberOfIntegers; i++) {
generatedSequence[i] = rand() % inputRangeOfIntegers + 1;
cout << generatedSequence[i] << " " << endl;
}
}
void Guess::beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Call our generateSequence function.
generateSequence(inputRangeOfIntegers, inputNumberOfIntegers);
/// Declare guess size based on user input.
inputGuess = new int[inputNumberOfIntegers];
/// Begin endless loop for user to guess integers.
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}
}
My issue is: I cant retrieve that sum variable in the main class to check it against the number of integers. Because if they are equal, then the program knows the user has guessed correctly. I cant use cout after calling the beginGuessingGame function either..
Any suggestions?
Thanks.
At least this part of the program
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) { //...
does not make sense. The program has undefined behavior.
Data members of the class object guess are not initialized So the member function getSum returns an indeterminate value of the data member sum of the object. And this indeterminate value is compared with another indeterminate value of the uninitialized variable numberOfIntegers in the while loop.
In the function generateSequence it seems there is a typo in this statement
generatedSequence = new int[inputRangeOfIntegers];
There should be
generatedSequence = new int[inputNumberOfIntegers];
Within the function beginGuessingGame there is an infinite loop
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}
Related
Newer to coding and im stuck, Need to make a array thats stores 5 numbers (1-9), then i need to check that array for duplicates if there is duplicates i need to replace that number either with a whole new random line no duplicates (seems like the easier option) or just replace that one number,
after that wants me to get users 5 numbers guess store that in a array, display that array at the bottom along with these under each of the numbers
// The * = means the number is in the exact location
// The - = means the array does not contain that number
// The + = means the array contains the number but its not in the right location
All the arrays want the digits to be entered one at a time
repeat steps till user gets all the numbers to * then end game with completion msg.
My true problem lies with step 4 and step 7;
Below is the code ive been working on today but any help would be truly appreciated
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void game_instructions(int n);
bool search_array(int a[], int n, int t);
int main()
{
//Step 1: Declare your variables and constants
const int SIZE = 5; //this constant stores the length/size of the code
int randcode[SIZE]; //this array stores the code generated randomly by the computer
int guess[SIZE]; //this array stores the code inputted by the player/user
//you may add more variables as needed
//Step 2: Output game instructions by calling function game_instructions
game_instructions(SIZE);
//Step 3: Generate a random code and store it in the array randcode one digit at a time.
//Each digit should be between 0 and 9 and should be stored as one array element
//Recall that rand() % 10 can be used to generate a number between 0 and 9
srand(time(0));
for(int i=0;i<SIZE;i++)
randcode[i]= (rand() % 10); //Computers random 5 numbers generated
cout<<"\nRandom C-numbers::"<<endl;
for(int i=0;i<SIZE;i++)
cout<<randcode[i] << " ";
//Step 4: Repeat step 3 if the array randcode contains duplicates
//You must use function contains_duplicates to implement this step
//Step 5: Ask the user for his guess and store it in the array guess.
//Read one digit at a time, validate it to make sure it is between 0 and 9, and store it as one array element
for (int i=0; i<SIZE; i++) {
cout<<"\nEnter Digit "<< i+1 << ": ";
cin >> guess[i];}
cout << endl;
//Step 6: Output the array guess on a single line with a space after each element (see the sample output provided)
for (int n=0; n < SIZE; ++n) {
cout << guess[n] << " ";
}
//Step 7: Compare the randomly generated code (randcode) with the user's guess (guess)
//and display feedback for each digit as: *, + or –, as explained below:
//For each digit in the user's guess do the following:
// If it matches the digit from the random code (both value and position), output *
// Otherwise, if it appears anywhere in the random code, output + (use function search_array here)
// Otherwise, output -
//Step 8: Repeat steps 5,6,7 until all digits have been guessed correctly
//Step 9: Output congratulations message
cout << endl << endl;
cout << "Good job! You guessed the code!";
return 0;
}
void game_instructions(int n)
//This function outputs the game instructions.
//Its parameter n represents the length of the code.
{
cout << "A random " << n << " digit code has been generated. You have to guess it. \n";
cout << "For every digit you will receive feedback in the form of *, + or - \n";
cout << " * means the digit is in the code and it is in the correct position.\n";
cout << " + means the digit is in the code but it is not in the correct position.\n";
cout << " - means the digit is not in the code.\n";
}
bool search_array(int a[], int n, int t)
//This function searches the array a (of size n) for a target value t.
//If t is found in the array the function returns true; otherwise it returns false.
{
for (int i = 0; i < n; i++)
{
if (a[i] == t) return true;
}
return false;
}
bool contains_duplicates(int a[], int n)
//This function searches the array a (of size n) and returns true if the array contains duplicates; otherwise, it returns false.
{
for (int i = 0; i < n; i++)
{
//compare element a[i] with all the remaining elements from index i+1 to n
for (int j = i+1; j < n; j++)
{
if (a[i] == a[j]) return true;
}
}
return false;
}
I got most the side code done but im just stumped on how to get this array to match any help would be nice
Here is how I would implement the program to generate the number without duplicate:
Step3 would look like this:
int tempNumber;
int i = 0;
while (i < SIZE) {
tempNumber = (rand() % 10);
if (contains_duplicates(randcode, tempNumber, i) == false) {
// every time there is no duplicate we push and add i by 1;
randcode[i] = tempNumber; // Computers random 5 numbers generated
i++;
}
}
contains_duplicates function would look like this:
bool contains_duplicates(int arr[], int tempNum, int currentArrSize)
// This function searches the array a (of size n) and returns true if the
//array
// contains duplicates; otherwise, it returns false.
{
for (int j = 0; j <= currentArrSize; j++) {
// if the array[index] not equal generated number the loop will
//iterate again without going to the line below
if (arr[j] != tempNum) {
continue;
}
// if the array[index] equal the function will return true and end
//the function
// uncomment this to check how many time it duplicate (not
//necessary tho)
//cout << "if return true, this will appear"<< endl;
return true;
}
// if the loop is done and no duplicate, function will return false
return false;
}
With this method it is not necessary to do step 4 because we already prevent duplicate array!
Here is the last problem from your question which is step 7:
cout << endl;
for (int i = 0; i < SIZE; i++) {
if (guess[i] == randcode[i]) {
cout << "* ";
} else if (search_array(randcode, SIZE, guess[i])) {
cout << "+ ";
} else {
cout << "- ";
}
}
Seems like the problem has been solved, now try to implement step 8 by yourself, good luck :)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
#include <iostream>
#include <string>
using namespace std;
bool custNum(char [], int);
int main()
{
const int size = 8;
char custmor[size];
cout << "Enter a customer number in the form ";
cout << "LLLNNNN\n";
cout << "(LLL = letters and NNNN = numbers): ";
cin.getline(custmor, size);
if(custNum(custmor, size))
cout<<"That's a valid id number"<<endl;
else
cout<<"That's not a valid id number"<<endl;
return 0;
}
bool custNum(char custNum[], int size)
{
int count;
for(count = 0; count<3; count++)
{
if(!isalpha(custNum[count]))
return false;
}
for(count = 3; count <size - 1; count++) //3<7 , 4
{
if(!isdigit(custNum[count]))
return false;
}
return true;
}
so I want to loop through a character array of 3 letters and 4 numbers like ABC1234, but I didn't get the condition of the second for loop (size - 1). How does it work every time it tests the condition?
Never use count as a loop variable. A good name for a loop variable is i.
Never declare variables away from their initialization. The above should be for( int i = 0; ... in both cases.
i < size - 1 is probably wrong. What you probably want is i < size.
Anyhow, it would help if you showed how size is declared, how it is initialized, etc. It would also help if you showed the exact text you are trying to parse. It would also help if you explained exactly what you expected to happen, and exactly what happened instead. I might amend my answer when you do that.
you read only amount of characters that size variable specify,
since then , Why custNum function would not return true for anything longer than size variable ? , Because it's not checking anything more than what size variable specify.
Below is the code you need
#include <iostream>
#include <string>
using namespace std;
bool custNum(string,unsigned int);
int main()
{
const unsigned int size = 8;
//char custmor[size];
string mystring;
cout << "Enter a customer number in the form ";
cout << "LLLNNNN\n";
cout << "(LLL = letters and NNNN = numbers): ";
cin >> mystring;
cout << mystring <<endl << " " << mystring.length() << endl;
// cin.getline(custmor, size);
if(custNum(mystring , size))
cout<<"That's a valid id number"<<endl;
else
cout<<"That's not a valid id number"<<endl;
return 0;
}
bool custNum(string s, unsigned int size)
{
unsigned int count;
if (s.length() != (size + 1))
return false;
for(count = 0; count<3; count++)
{
if(!isalpha(s[count]))
return false;
}
for(count = 3; count <size - 1; count++) //3<7 , 4
{
cout << s[count] <<endl;
if(!isdigit(s[count]))
return false;
}
return true;
}
I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm new to C++ and trying to create a lottery game for a college project.
I have a for loop to check that there are no duplicate numbers in the array entered. This works absolutely fine when you take out the section of code to produce the random numbers.
As soon as I add the random number section back in, the for loop just gets stuck. It will continuously tell me that i have already entered the number when its trying to store the first number.
I have attached all of my code, apologies if you don't need it all.
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
using namespace std;
//int loto[6];
int main()
{
int numbers[6];
//void rand_num(int loto[6], int count);
int loto[6]; //used to store the loto numbers
//int james = 0;
//int l,j; //used in checking any duplicated
srand(time(0));
for(int count=0; count<6; count++)
{
loto[count] = (rand()%49)+1;
cout << loto[count] << endl;
}
//declares the variable i to increase each time a number is entered.
//this will only go as high as 6
for(int i=0;i<6;i++)
{
cout<<" " << i<<" : Please enter your lottery numbers: "<<endl;
cin>>numbers[i];
if ((numbers[i] >= 50) | (numbers[i] == 0))
do
{
{
//checks to see if the first number entered is above 50 or = to 0 and rejects it
cout << "The Number must be between 1-49, please select again. " << endl;
cin >> numbers[i];
}
}
while ((numbers[i] >= 50) | (numbers[i] == 0));
//----------------------------------------------------------------------------
//this section of code is a loop within a loop to check the number entered against all numbers already stored.
//makes l the same as i effectively
for(int l=0;l<6;l++)
{
//makes j one more than l
for(int j=l+1;j<7;j++)
{
if( numbers[l] == numbers[j] )
do
{
{
cout << "Number has already been chosen, please re-enter number " << endl;
cout << endl;
cin >>numbers[i];
//checks the number that is re-entered is not <50 or = 0
//if so it rejects it and asks for another as above.
if ((numbers[i] >= 50) | (numbers[i] == 0))
do
{
{
cout << "The Number must be between 1-49, please select again. " << endl;
cin >> numbers[i];
}
}
while ((numbers[i] >= 50) | (numbers[i] == 0));
}
}
while (numbers[l] == numbers[j]);
}
}
}
//----------------------------------------------------------------------------
//this displays the numbers that have been chosen.
cout << "Your Numbers are: " << endl;
for (int i = 0; i<6; i++)
{
cout << " " << numbers[i];
}
return 0;
}
I'm not sure this is the real problem but it is a bug. Try to correct it and see if it helps.
for(int l=0;l<6;l++)
{
//makes j one more than l
for(int j=l+1;j<7;j++)
{
if( numbers[l] == numbers[j] )
The inner-loop will reach j==6 so you will access outside the array. The outer-loop shall have 5 as the limit and the inner-loop shall have 6 as the limit.
EDIT:
After looking a bit more at your code I can see that you are using numbers[] without initializing it. The two nested for-loops will compare all elements in numbers. But if the user have only entered 2 numbers, the rest is unitialized and can give unintended results.
Further - you don't need to check all elements againt all elements every time. Just check the newly entered number (index by i) with all previous numbers.
Finally you will probably need something like:
if (!(cin >> numbers[i])) {
cout << "Please enter numbers only." << endl;
cin.clear();
cin.ignore(10000,'\n');
}
to handle input not being integer, e.g. "text"
And to minor things:
You should also check for negative numbers.
You are using | instead of ||. It will work fine but || seems more correct as it is the logical OR (while | is a binary OR).
#include <iostream>
using namespace std;
void displayListValues(int Array[], int Max)
{
int counter = 0;
for (int i = 0; i < Max; i++)
{
cout << counter << " = " << Array[i] << endl;
counter++;
}
}
void main()
{
const int Max = 1000;
int Array[Max]; // this is where I couldn't figure out what to change so the array isn't so huge
int counter = 0;
cout << "Enter Numbers. If finished, enter a negative number to continue" << endl;
do
{
cin >> Array[counter];
if (Array[counter] < 0)
break;
} while (counter < Max);
displayListValues(Array, Max);
}
details details details, any assistance would be fantastic!!! Thanks guys!!!! :D :D :D
I don't know what else to include in here because it keeps saying my post is mostly code. I apologize for this nonsensical gibberish at the bottom of the post.
Short answer is you can't. C/C++ arrays are a fixed size once defined.
The long answer is you need to use something other than an array. You should use a std::vector, this behaves similar to an array but can be resized.