I'm trying to create a number guessing game where the user enters number integers they want to guess and the range of those integers 1 to (m). Then the computer randomly generates numbers in that range for the user to guess. The user guesses until they get all the numbers correct For example:
Enter number integers: 4
Enter the range of those integers from 1 to (m): 6
Enter guess: 2 3 1 4
3 of your guesses are correct. Guess Again
Enter guess: 2 3 1 6
Correct. Would you like to play again.
The Output I get right now is:
Enter number integers: 4
Enter the range of those integers from 1 to (m): 6
Enter your guesses for the 4 in the range from 1 to 6 that you have selected: 2 3 1 4
Then after you enter the guesses nothing else happens with the program. I'm confused on why the game is not saying how many guesses where correct.
I don't understand what I'm doing wrong to get this output. I'm also getting no warnings or errors from my code.
There are three files for this game.cpp, game.h, and driver.cpp. Please let me know if you find anything else wrong with my code. This is my 1st program I have wrote in C++.
//game.cpp
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "Game.h"
#include <iostream>
#include <iomanip>
using namespace std;
//---------------------------------------------------------------------------------------------
// generateNumbers: Fucntion to generate numbers between 1 to (m) and
// generate as many has user wanted.
// n: the amount of integers
// m: the max number the user wants
// numbers: returns the numbers generated by the computer
//---------------------------------------------------------------------------------------------
int*Game:: generateNumbers(int n, int m) {
// Intialize random number
srand(static_cast<unsigned int>(time(NULL)));
// Declare array size to generate random numbers based on what is between 1 to (m)
int* numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = (rand() % m) +1;
cin >> numbers[i];
}
return numbers;
}
//-----------------------------------------------------------------------------------------------
// guessingGame: See's how many numbers the user got to correct until they win the game.
// n: the amount of integers
// m: the max number the user wants
//-----------------------------------------------------------------------------------------------
void Game::guessingGame(int n, int m) {
int* p;
int sum = 0;
// Call the generateNumber function
generateNumbers(n, m);
// Declare array based on user guesses
inputGuess = new int[n];
p = generateNumbers(n,m);
// Loop for User guesses for the integers
for (int i = 0; i < n; i++) {
cin >> inputGuess[i];
}
// See if the user guesses and computers answers match up
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (p[i] == inputGuess[j]){
sum++;
break;
}
}
}
}
------------------------------------------------------------------------------
//driver.cpp
#include <iostream>
#include "Game.h"
using namespace std;
int main()
{
//Declare variables
Game guess;
int n;
int m;
int userNumbers = guess.getNumbers();
// Prompt the user to enter integers and range
// Have user enter number of integers they want
cout << "Enter the Number of the Integers (n): ";
cin >> n;
// Have user enter the range if integers between 1 to m
cout << "Enter the Number of Each Integers from 1 to (m): ";
cin >> m;
// guesses from user are not correct then user needs to keep guessing
while (userNumbers != n) {
cout << "Enter your guesses for the " << n << " " << "in the range from 1 to " << m << " " << "that you have been selected: ";
cin >> userNumbers;
guess.guessingGame(n, m);
}
// If the user has guessed the correct numbers and would like to play again
if (sizeof(userNumbers) == n) {
cout << "You are correct! Play Again?";
}
// If numbers guessed not correct then display how many are correct
else {
cout << sizeof(userNumbers) << "of your guesses are correct." << endl;
}
};
---------------------------------------------------------------------------------
//game.h file
class Game{
public:
// Get what numbers the users have guessed are correct
int getNumbers() {
return number;
}
// Generate random numbers between the range set by user
int* generateNumbers(int n, int m);
// Begin the guessing game
void guessingGame(int n, int m);
private:
int number; // numbers that are correct
int* randomNumbers; // random numbers generated
int* inputGuess; // users guesses
};
There are lots of issues in your code.
srand should not be called each time you want to roll random numbers, but only once (eg in main)
rand is of poor quality. In addition to that, distributions obtained via % are usually not uniform (suppose largest random number is ...108 then %10==9 will have one count less than %10 == i). Take a look at <random> if you need better randomness.
inputGuess = new int[n]; for dynamic arrays is problematic. When a class manages a resource (eg a dynamically allocated array) it must follow the rule of 3/5 or it must be considered broken (in particular, copying your Game will cause problems). Prefer the rule of 0 (same link) when possible and use std::vector instead.
also because of inputGuess = new int[n];, your code has lots of memory leaks. If you really do use new you must delete anything that was created via new. Here a vector is the right choice, other uses of new are covered by smart pointers.
The logic of the code is difficult to decipher, mainly because you seem to confuse int with arrays and 2d arrays of ints.
I could probably continue the list, but anyhow I suggest you to start from scratch. You wrote to much code at once and now are faced with lots of issues. Try to test more. Make a plan of what you want to implement, write a test (that can only fail for now), then write the code that makes the test pass. In this way you always have to deal with at most one or two problems, not all at once.
To give you only a rough sketch of how your code could look like with std::vector:
#include <cstdlib>
#include <ctime>
#include <vector>
#include <iostream>
#include <algorithm>
struct Game {
Game(size_t num,int min,int max){
for (size_t i=0;i<num;++i) hiddenNumbers.push_back( rand()%(max-min) + min);
}
void reveal(){
for (const auto& n : hiddenNumbers) std::cout << n << " ";
std::cout << "\n";
}
bool guess(int x){
--num_guesses;
auto it = std::find(hiddenNumbers.begin(),hiddenNumbers.end(),x);
if (it == hiddenNumbers.end()) return false;
hiddenNumbers.erase(it);
return true;
}
bool has_more_guesses(){ return num_guesses > 0; }
int remaining() { return num_guesses; }
private:
int num_guesses = 5;
std::vector<int> hiddenNumbers;
};
int main(){
srand(static_cast<unsigned int>(time(NULL)));
Game g{10,2,5};
while (g.has_more_guesses()) {
bool correct = g.guess(2);
if (correct) std::cout << "Yay. Guessed numbeer was corerct! \n";
std::cout << "you have " << g.remaining() << " remaining guesses\n";
std::cout << "spoiler altert! Secret numbers are: ";
g.reveal();
}
}
Each game has maximum 5 trials. If you still continue to call guess the counter num_guesses will get negative. You might want to fix that. When a number is found guess returns true and the number is erased from the private vector.
Possible output:
Yay. Guessed numbeer was corerct!
you have 4 remaining guesses
spoiler altert! Secret numbers are: 3 4 2 2 3 4 4 2 3
Yay. Guessed numbeer was corerct!
you have 3 remaining guesses
spoiler altert! Secret numbers are: 3 4 2 3 4 4 2 3
Yay. Guessed numbeer was corerct!
you have 2 remaining guesses
spoiler altert! Secret numbers are: 3 4 3 4 4 2 3
Yay. Guessed numbeer was corerct!
you have 1 remaining guesses
spoiler altert! Secret numbers are: 3 4 3 4 4 3
you have 0 remaining guesses
spoiler altert! Secret numbers are: 3 4 3 4 4 3
Related
#include<iostream>
using namespace std;
int main(){
int N,i;
int count=0;
cin>>N;
for(i=1;i<=N;i++){
if(N%i==0){
cout<<i<<" ";
count++;
}
}
}
INPUT 6
OUTPUT 1 2 3 6
4
I want to print the Number of Factors which is 4 in this case Before the Factors. I did it few days ago but i forget that now please help me..
The easiest way to achieve what you want by putting the factors in the array.
like:
int k =0 ;
arr[k++] = i;
now,
first print the count and then traverse and print the array.
There is no need to cout on line 12 and it will work fine :). That is printing the "i" which are the numbers you don't need.
cout<<i<<" ";
This line remove it.
Edit: I reread and found that you wanted to print the factors after it. You could save it in a vector or an array.
#include <vector> // At the top of your program
std::vector<int> factors; // At the declaration step
factors.push_back(i); // Where your cout << "i" initially was
// After the cout of your count
for ( auto &factor : factors ){
std::cout << factor << " ";
}
Im trying to create a number guessing game where the user enters number integers they want to guess and the range of those integers 1 to (m). Then the computer randomly generates numbers in that range for the user to guess. The user guesses until they get all the numbers correct For example:
Enter number integers: 4
Enter the range of those integers from 1 to (m): 6
Enter guess: 2 3 1 4
3 of your guesses are correct. Guess Again
Enter guess: 2 3 1 6
Correct. Would you like to play again.
The Output I get right now is:
Enter number integers: 4
Enter the range of those integers from 1 to (m): 6
Enter your guesses for the 4 in the range from 1 to 6 that you have selected: 2 3 1 4
There are three files for this game.cpp, game.h, and driver.cpp. Please let me know if you find anything else wrong with my code. This is my 1st program I have written in C++.
//game.cpp
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "Game.h"
#include <iostream>
#include <iomanip>
#include <vector>
//---------------------------------------------------------------------------------------------
// generateNumbers: Fucntion to generate numbers between 1 to (m) and
// generate as many has user wanted.
// n: the amount of integers
// m: the max number the user wants
// numbers: returns the numbers generated by the computer
//---------------------------------------------------------------------------------------------
std:: vector<int> Game::generateNumbers(int n, int m) {
// Declare array size to generate random numbers based on what is between 1 to (m)
std::vector<int> random_numbers;
int numbers;
// Randomly generate n intgers between 1 to (m)
for (int i = 0; i < n; i++) {
numbers = (rand() % m) + 1;
random_numbers.push_back(numbers);
}
return random_numbers;
}
//-----------------------------------------------------------------------------------------------
// guessingGame: See's how many numbers the user got to correct until they win the game.
// n: the amount of integers
// m: the max number the user wants
//-----------------------------------------------------------------------------------------------
void Game::guessingGame(int n, int m) {
// Declare variables
std::vector<int> pointer;
int correct_answers = 0;
// Set inputGuess equal to a vector which is teh size of n
std::vector<int> inputGuess;
inputGuess.resize(n);
pointer = generateNumbers(n, m);
// Get user guesses integers
for (int i = 0; i < n; i++) {
std::cin >> inputGuess[i];
}
// See if the user guesses and computers answers match up
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (pointer[i] == inputGuess[j]) {
correct_answers++; //counts how many numbers the user got correct
}
}
}
}
// driver.cpp
#include <iostream>
#include "Game.h"
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <iomanip>
#include <vector>
int main()
{
//Declare variables
Game guess;
int n; // number of integers
int m; // max value for integers
int guesses;
std::vector<int> userNumbers;
std::srand(static_cast<unsigned int>(time(nullptr))); // Intialize random number
// Prompt the user to enter integers and range
// Have user enter number of integers they want
std::cout << "Enter the Number of the Integers (n): ";
std::cin >> n;
// Have user enter the range if integers between 1 to m
std::cout << "Enter the Number of Each Integers from 1 to (m): ";
std::cin >> m;
// guesses from user are not correct then user needs to keep guessing
while (userNumbers.size() != n) {
std::cout << "Enter your guesses for the " << n << " " << "in the range from 1 to " << m << " " << "that you have been selected: ";
for (int i = 0; i < n; i++) {
userNumbers.push_back(n);
guess.guessingGame(n,m);
}
}
// If the user has guessed the correct numbers and would like to play again
if (userNumbers.size() == n) {
std::cout << "You are correct! Play Again?";
}
// If numbers guessed not correct then display how many are correct
else {
std::cout << sizeof(userNumbers) << "of your guesses are correct." << std::endl;
}
};
// game.h
#include <vector>
class Game {
public:
// Get what numbers the users have guessed are correct
std::vector<int> getNumbers() {
return correct_number;
}
// Generate random numbers between the range set by user
std:: vector<int> generateNumbers(int n, int m);
// Begin the guessing game
void guessingGame(int n, int m);
private:
std::vector<int> correct_number; // numbers that are correct
std::vector<int> input_guess;
};
The line
inputGuess.push_back(n);
adds only one element, but you are using n elements here:
// Get user guesses integers
for (int i = 0; i < n; i++) {
std::cin >> inputGuess[i];
}
Therefore an out-of-range access happens when n is larger than 1.
To set the number of elements to n, you should use resize() instead like this:
inputGuess.resize(n);
I've set my array size to 20 (I set it to 19 assuming it's counting 0). I set my for loop to only run so long as gradeCount <= to gradeCounted yet it will keep running no matter how many times I enter data. If I enter 3 grades without pressing enter between each one, such as "23 23 23" it will return "Enter Grade" 3 times in a row, rather, for as many grades as I enter, separated by spaces. I don't understand why it's not passing data into the array and ending the for loop properly. I'm sure my code is an ugly mess, sorry.
Also, when entering code into stackoverflow, it said to indent the code 4 spaces to format? I couldn't initially indent the code with the code button and there was no {} button either. What am I missing? It was only after a notification to fix it that I was able to. Thanks for your time, I don't want to be a pain in the ass for you guys.
//This program asks user how many grades there are, inputs grades, and displays median of said grades.
#include <iostream>
using namespace std;
//Variables
////////////////////const int limitGrades = 20; //Array "boxes"? //Ignore this //for now.
int gradeCounted; //Number of grades from user.
const int SIZE = 19;
//Array
float grades[19]; //Max grades that can be entered.
//Functions
void gradeTaker()
{
cout << "You may input up to 20 grades. \n";
cout << "First enter the number of grades you have: \n";
cin >> gradeCounted;
//requests how many grades there are and stores them in array
for (int gradeCount = 0; gradeCount <= gradeCounted + 1; gradeCount++)
{
for (float &grade : grades)
{
cout << "Enter grade: \n";
cin >> grade;
}
}
};
int main()
{
gradeTaker();
cout << "grades so far";
for (int grade : grades)
cout << grade << endl;
system("pause");
}
The size of the array is separate from how you access it. Accessing 20 values is the equivalent to accessing indices from 0 to 19.
float grades[20];
for(size_t i = 0; i < 20; i++){ // print all values of grades
std::cout << grades[i] << "\n";
}
Furthermore, your for loop in gradeTaker will ask you for a value for each index of grades a total of gradeCounted + 2 times. To fix this, only iterate over the indices that you're assigning a value to like so:
for (int gradeCount = 0; gradeCount < gradeCounted; gradeCount++){
cout << "Enter grade: \n";
cin >> grade[gradeCount];
}
Finally... the for loop in your main function will iterate across the entire array which may include uninitialized values. You should initialize the array or use a dynamic data structure like std::vector and just push_back the necessary values.
(P.s. highlight code in the text-block and press CTRL+K to indent.)
I want the program to read my file. I want to count all the numbers in the document that are greater than 175 and that are even using a switch statement. Or is there any better way to do it? Also wanting to know where I can get help with learning C++ since I am new to this? This is what I came up with but my program seems to not execute. This part of a bigger coding program. I want to know if it is possible to create multiple commands in the switch statement. I need help with case 0 on switch(num%2).
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main ()
{ //Listing all my variables
int num;
double even;
int evencount = 0;
int evencountext = 0;
double big;
int bigcount = 0;
double sm;
int smcount = 0;
double odd;
int oddcount = 0;
double small;
double large;
double average;
double total;
int amount = 0;
string filename;
ifstream inFile; //Input and output data from a file
ofstream outFile;
inFile.open("integers.dat"); //Open the integers.dat
if (!inFile) //Closes if the program does not exist.
{
cout << "No File Found! Closing Program." << endl;
return 1;
}
cout << "Welcome to Wake's Integer Processing Agency \n" << endl; //First line of output
cout << "What is the name of your file? "; //Get the name of the file from user
cin >> filename;
cout << endl;
inFile >> num; // Get the first number from the file
large = num; // Copy the number to the large and small variables to give the number something
small = num; // to compare them to.
while (inFile) //Main loop designed to grab numbers continuosly until the file ends.
{
switch (num % 2) //This switch divides the each number in the file by two and examines the remainder
{
case 0: // If the remainder is zero, this means the number is even
evencount++; // Increase the counter for even by one
if(num >= 175)
{evencountext++;};
even = even + num; // And the even number to the variable for total even numbers
break;
case 1: // If remainder is positive or negative one, this means the number is odd
case -1:
oddcount++; // Increase total odd numbers by one
odd = odd + num; // Add the odd number to the variable for total odd numbers
}
cout << evencountext<< endl;
cout << "The sum of the odd integers is " << odd << endl;
inFile.close(); //close the integers.dat file
return 0; //close program
}
}
It is better to use if statement remainder could be anything
if (num % 2 == 0){ // If the remainder is zero, this means the number is even
evencount++; // Increase the counter for even by one
if(num >= 175){
evencountext++;
even = even + num; // And the even number to the variable for total even numbers
}
}else{ // If remainder is not zero, this means the number is odd
oddcount++; // Increase total odd numbers by one
odd = odd + num; // Add the odd number to the variable for total odd numbers
}
Switches and if/else are flow control tools. If/else statements evaluate true/false, whereas switches require integer inputs and tests it against other values; uniformly.
Since you want to run multiple tests per data, I recommend that you store the data acquired into a (temporary) variable so you apply whatever multiple tests you need.
Like others have posted you should use if statements when testing for truths, and switches when testing for matches.
As for tutorials:
My default two recommended:
Tutorial spot:
https://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm
CPlusPlus:
http://www.cplusplus.com/doc/tutorial/program_structure/
Code relative to original post:
#include <iostream>//Used for c++ Standard I/O stream
#include <fstream>//Used for c++ File I/O stream
//using namespace std;//Adding this will no longer require you to type any std::
//using std::cout;//Adding this will no longer require you to type std:: in front of cout
//using std::cin;//Adding this will no longer require you to type std:: in front of cin
//using std::fstream; " " "
int main()//Main Function:
{
//Declare and initialize fstream for input operations
std::fstream fs ("file.txt", std::fstream::in);//Open file for reading
//Declare integer variables and provide default values for accumulators/totals.
int large, small, num, even = 0, odd = 0, evenSum = 0, oddSum = 0;
//Declare boolean to test against first run; embedded initialization within loop.
bool first = true;
while(fs >> num) {//DATA stored into variable num.
//Print the number out for debugging (visual reading without debugger).
std::cout<<"The number: "<<num<<std::endl;
//Initialize our smallest number and largest number if not done so already.
if(first) {//Only occurs the first run
first = false;//Disables this test from here on.
small = large = num;
}
//Test if the number is larger than our largest.
if(num > large) {
large = num;
}
//Test if the number is smaller than our smallest.
if(num < small) {
small = num;
}
//Test if the number is 0 or 1. (0 and 1 are false and true, but not really).
if(num%2 == 0) {//If even:
++even;//Increment counter PRE
evenSum+=num;//Accumulate the total even values.
}else {//Else, were assuming it is odd (without having to check again).
odd++;//Increment counter POS; doesn't matter here
//but it does matter if on the stack.
oddSum+=num;//Accumulate the total odd values.
}
}//The end of the while loop. It retests the loop until satisfied.
//In a PRE loop it would leave the loop when false occurs.
//Make sure to always close the file after you're done using it.
fs.close();
//Printing the data:
std::cout<<"Number of even numbers: "<<even<<std::endl;
std::cout<<"Number of odd numbers: "<<odd<<std::endl;
std::cout<<"Sum of even numbers: "<<evenSum<<std::endl;
std::cout<<"Sum of odd numbers: "<<oddSum<<std::endl;
std::cout<<"Largest number: "<<large<<std::endl;
std::cout<<"Smallest number: "<<small<<std::endl;
//std::end produces newline and does some sub-procedure in clearing buffers.
return 0;
}
Sample Output:
The number: 123
The number: 456
The number: 222
The number: 21
The number: 1
The number: 50
The number: 22
Number of even numbers: 4
Number of odd numbers: 3
Sum of even numbers: 750
Sum of odd numbers: 145
Largest number: 456
Smallest number: 1
Sample Input:
123 456 222
21
1
50
22 a
d
55
I want to write a simple program where I ask the user to input a set of numbers to sum. The user can input an unknown number of numbers.
Here's my code:
#include <iostream>
using namespace std;
//ask the user to input a set of numbers to sum (unknown number of input)
int main (){
int sum = 0, value = 0;
while (cin >> value){
sum += value;
cout << "sum is " << sum << endl;
return 0;
}
}
However, when I input several numbers, the result always equal to the first number, not the sum of all numbers entered. As in:
5 6 7 8
sum is 5
What I am doing wrong?
The problem is return 0. Put it outside of the while block.
You are doing it wrong. You must have to put the print method outside of the loop and the return too.If you want user to terminate at any time he wants then you need to take input at an specific keyword or any other keyword other than the data type(like char at place of integer) , so that it will terminate the loop.
#include <iostream>
using namespace std;
int main (){
int sum = 0, value = 0;
/*press any key other than number to terminnate*/
while (cin >> value){
sum += value;
}
cout << "sum is " << sum << endl;
return 0;
}