So I was doing some beginner challenges and wanted to modify my code, this was what i did first.
#include <iostream>
#include <stdlib.h>
#include <time.h>
int random;
int guess;
int num_guess = 1;
int main(){
srand(time(NULL));
random = rand() % 100 + 1;
std::cout << "Try to guess my number between 1 and 100." << std::endl;
std::cin >> guess;
while(guess > random){
std::cout << "Sorry too high but i'll give you another try." << std::endl;
std::cin >> guess;
num_guess += 1;
}
while(guess < random){
std::cout << "Sorry too low but i'll give you another try." << std::endl;
std::cin >> guess;
num_guess += 1;
}
if(guess = random){
std::cout << "WOW! Congratulations you actually got it, you did use " << num_guess << " tries tho." << std::endl;
}
return(0);
}
It is supposed to generate a random number between 1 and 100, and then you guess what number it is. But then I copied this code over to another file under the same project because im doing this in school so I wanted all the different versions of my code for documentary purposes. But when I started writing the new code where the program is supposed to guess a number you give it between 1 and 100.
#include <iostream>
#include <stdlib.h>
#include <time.h>
int number;
int guess = 100;
int num_guess = 1;
int main(){
std::cout << "Please enter any number between 1 and 100" << std::endl;
std::cin >> number;
if(number > 100 && number < 1){
std::cout << "Enter a valid number" << std::endl;
std::cin >> number;
}
srand(time(NULL));
guess = rand() % guess + 1;
return(0);
}
I erased the old code from main.cpp and wrote this instead, but when I tried to run it i got these error messages:
multiple definition of `mainCRTStartup'
multiple definition of `WinMainCRTStartup'
multiple definition of `atexit'
multiple definition of `_onexit'
multiple definition of `__gcc_register_frame'
multiple definition of `__gcc_deregister_frame'
undefined reference to `_Jv_RegisterClasses'|
Guess you didn't exclude your old file from the project. In this case linker meets two main functions and doesn't know what to use. Possible ways to solve it:
exclude unused file from the project;
comment out old version;
use conditional compilation:
#ifdef OLD_VER
// main1
...
#else
// main2
...
#endif
create a new project;
use version control systems.
First 3 methods are not recommended for a long use. The last one is a good point (the best point, I think) but it can require elementary VCSs learning.
Related
So I have an assignment for class in which I have to ask the user for an integer in between 1 and 3000. Then my program should be able to tell if the integer is a prime number or not. Lastly, I would have to put that integer into a file, but only if it is a prime number. But my issue is my syntax, I am not sure if it's right(well actually obviously it's not because I keep getting errors). Is it possible to open a file in a function? and if so does it become a parameter?
I have been going through my textbook and googling as much as possible for some guidance but I'm still feeling lost. Any advice would help.
Edit: My logic as far as the numbers work, however when I add the code to write to a file, I'm now getting errors.
The two errors are
C2440 initializing: cannot convert from constant char to int (line 18)
C2079 myfile: uses undefined class'std::basic_fstream <>char,std::char_traits>'
Here's my code so far!
// Project 5.cpp : Defines the entry point for the console application.
//
#include <fstream>
#include "stdafx.h"
#include <iostream>
using namespace std;
//functions
void prime(int x);
//variables
int x=0;
int i;
char answer;
fstream myfile("castor_primes.txt");
int main()
{
do
{
cout << "Enter an integer between 1 and 3000 \n";
cin >> x;
if (x == 1)
{
cout << x << " is not a prime number.\n";
}
else if (x < 1 || x>3000)
{
cout << x << " is an invalid number. \n";
}
else
{
prime(x);
}
cout << "Do you want to enter another number? Y/N \n";
cin >> answer;
} while (answer == 'y' || answer == 'Y');
myfile.close();
return 0;
}
void prime(int x)
{
if (x == 2)
{
cout << "Yes, " << x << " is Prime\n";
}
else
{
for (i = 2; i < x; i++)
{
if (x%i == 0)
{
cout << x << " is not a prime number\n";
break;
}
}
if (x == i)
{
cout << "Yes, " << x << " is Prime\n";
myfile << x ;
}
}
}
#include "stdafx.h" includes a pre-compiled header file when using Microsoft Visual Studio. Check to see if that file exists and if it is correct (depending on the errors you see).
There is no reason to pass the outputFile into the prime() function since you are opening and closing it in the function. Although it works just fine if you do.
It is a parameter of the function call (if that is your question) and is a global variable since it is defined outside the main() function.
As some one else suggested the code functions if the aforementioned #include "stdafx.h" is removed, but I am not sure how that affects the compilation in Visual Studio.
I am stuck on this random guessing game for school.
I have added the code that needed to be added, but the console keeps closing without returning the last strings.
I would also like to learn how to make the program run again with clicking Y to run again.
I am still learning C++, so any help would be appreciated.
Code:
// GuessingGameApp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>//added to run string
#include <locale>//added toupper run again
using namespace std;
int main()
{
//Seed the random number generator
srand(time(0));
int selectedNumber = rand() % 20 + 1; int numberOfTries = 0;
int inputtedGuess;
std::cout << "Guess My Number Game\n\n";
//Ask the user for a value until the correct number is entered
do {
std::cout << "Enter a guess between 1 and 20:";
std::cin >> inputtedGuess;
++numberOfTries;
if (inputtedGuess > 20 || inputtedGuess < 1) {
cout << "Your guess is out of range.\n\n";
}
else if (inputtedGuess > selectedNumber) {
cout << "Too high!\n\n";
}
else if (inputtedGuess < selectedNumber) {
cout << "Too low!\n\n";
}
}
while (inputtedGuess != selectedNumber);
//Congratulate the user and end the program
std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" << std::endl;
//fix problem with console closing and (add "play again" option), so I can
//learn
//printf; did not work... Break did not work..
//
return 0;
}
I was able to get the console to stay open by putting a break at line 33, but I want to learn how to do this correctly so I deleted the break.
The last line of your output should actually be printed. The reason why the last line "is not printed" is probably that your IDE closes the console before you can see the final output (though it should be there). Many IDEs allow to make the console visible after program termination. BTW: Note that when pasting the code you probably lost a << before std::endl in std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" std::endl; But this has actually to be a copy-paste problem, because your program would not have compiled otherwise.
Anyway, by providing a "Try again?"-logic, your program does not terminate and the problem is solved.
I'd suggest to provide a separate function performing the guess, which is then called in a do-while loop with the "Try again="-question.
void guess() {
// your code (except srand) goes here...
}
int main() {
srand(time(0)); //Seed the random number generator only once
char doAgain;
do {
guess();
cout << "Try again (Y/N)?";
cin >> doAgain;
}
while (toupper(doAgain)=='Y');
return 0;
}
As people suggested, you can add another do-while loop to repeat the game.
int choice = 0;
do {
// first part of code..
do {
// inner do-while
} while (inputtedGuess != selectedNumber);
std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" std::endl;
cout << "\nWould you like to play again?\n\n";
cout << "1 - Yes\n";
cout << "2 - No\n\n";
cout << "Choice: ";
cin >> choice;
} while(choice == 1);
So as the title describes I'm trying to learn PRNG but it hasn't gone too well thusfar. I am writing a program that takes an entered number of choices, rolls a dice and makes the choice for you. I do this using rand() and an array of strings with a length that is dependant on a variable read in before the declaration of the array.
The two problems showing up are that if I try to choose between for example 12 choices, the program will crash. As I read in the length of the array before I declare it I don't understand how this could happen. Also the PRNG will always return the number 2 which is not the desired function of a function that should return a random number between min and max. I will share my code below:
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
#include <string>
using namespace std;
int callPRNG(int min, int max)
{
srand(static_cast<unsigned int>(time(0))); // set initial seed value to system clock
static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0); // static used for efficiency, so we only calculate this value once
// evenly distribute the random number across our range
return static_cast<int>(rand() * fraction * (max - min + 1) + min);
}
int main()
{
int max=1;
int min=0;
cout << "Please enter the amount of choices you want to choose from: ";
cin >> max;
string choices[max-1];
int choiceMade=0;
{
int i=0;
while(i<=max-1)
{
cout << "Please enter choice " << i+1 << ": ";
cin >> choices[i];
i++;
}
choiceMade=callPRNG(min, max-1);
cout << "I have decided: " << choices[choiceMade-1];
}
return 0;
}
As extra information, I'm using code::blocks with C++11 enabled on a windows 10 OS. I hope someone can help me with this as I don't quite understand arrays and PRNG well enough to find the error by myself. Thanks :)
edit: It seems, as I can now use higher values for max without crashing the program, that the answer scales with the value of max.
The problem with crashing is because you're not allocating enough space for the array of choices (you need the size to be max, not max - 1). You're using a G++ extension to C++ — namely variable length arrays — which are part of standard C but not standard C++. You should use a vector of strings.
The non-random random behaviour is more a reflection on the quality of the rand() PRNG — it is often not very good. I was getting similar behaviour on macOS Sierra 10.12.2 with G++ 6.3.0. I worked around it by avoiding the use of floating point arithmetic and using modulus operations.
The use of choiceMade-1 was suspect too; given a choice of 0, it tries to access non-existent element -1 of the array of choices.
These changes yield the following code, which still has debug code in place:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
int callPRNG(int min, int max)
{
cout << __func__ << ": " << min << " .. " << max << "\n";
unsigned int seed = static_cast < unsigned int > (time(0));
cout << __func__ << ": " << seed << "\n";
srand(seed);
int range = max - min + 1;
int max_valid = RAND_MAX - RAND_MAX % range;
int rand_val;
while ((rand_val = rand()) > max_valid)
;
int rv = rand_val % range;
cout << __func__ << ", rand_val = " << rand_val << ", ret_val = " << rv << "\n";
return rv;
}
int main()
{
int max = 1;
int min = 0;
cout << "Please enter the amount of choices you want to choose from: ";
cin >> max;
vector < string > choices(max);
int choiceMade = 0;
int i = 0;
while (i <= max - 1)
{
cout << "Please enter choice " << i + 1 << ": ";
cin >> choices[i];
i++;
}
choiceMade = callPRNG(min, max - 1);
cout << "I have decided: " << choices[choiceMade] << endl;
return 0;
}
Sample outputs:
Please enter the amount of choices you want to choose from: 12
Please enter choice 1: a
Please enter choice 2: b
Please enter choice 3: c
Please enter choice 4: d
Please enter choice 5: e
Please enter choice 6: f
Please enter choice 7: g
Please enter choice 8: h
Please enter choice 9: i
Please enter choice 10: j
Please enter choice 11: k
Please enter choice 12: l
callPRNG: 0 .. 11
callPRNG: 1483236759
callPRNG, rand_val = 770034137, ret_val = 5
I have decided: f
Over a series of runs, with filtering out all except the 'I have decided' lines, I got outputs:
I have decided: g
I have decided: i
I have decided: d
I have decided: f
I have decided: a
I have decided: c
I have decided: l
I have decided: f
I have decided: a
I have decided: f
I have decided: h
Jonathan Leffler's answer was complete and correct. But I thought you might also be interested in a shorter program that uses <random>:
#include <vector>
#include <iostream>
#include <string>
#include <random>
size_t callRNG(size_t min, size_t max)
{
std::random_device r{};
std::uniform_int_distribution<size_t> ud{min,max};
return ud(r);
}
int main()
{
const auto min{0};
std::vector<std::string> choices{};
std::string line{};
while(std::cout << "Please enter choice: ", std::getline(std::cin, line) && !line.empty()) {
choices.push_back(line);
}
const auto max{choices.size() - 1};
if(!choices.empty()) {
std::cout << "I have decided: " << choices[callRNG(min, max)] << '\n';
}
}
I am running this code from textbook: An Intro To Design Patterns in C++ with QT.
/* Computes and prints n! for a given n.
Uses several basic elements of C++. */
#include <iostream>
int main() {
using namespace std;
/*
*/
// Declarations of variables
int factArg = 0;
int fact(1);
do {
cout << "Factorial of: ";
cin >> factArg;
if (factArg < 0) {
cout << "No negative values, please!" << endl;
}
}
while (factArg < 0);
int i = 2;
while (i <= factArg) {
fact = fact * i;
i = i + 1;
}
cout << "The Factorial of " << factArg << " is: " << fact << endl;
return 0;
}
The output console only prints one line that says "Factorial is: "
Is that what it's suppose to do?
Yes that is what the program should output at first; it's waiting for you to type a number. If you would step into your code you would soon find out that it will wait for an input on the following line " cin >> factArg;".
So... Go ahead, type a number and press enter :).
Yes you code includes cin >> factArgwhich you will input in the terminal first before the program will run. You may want to put the using namespace std before the main function rather then in it.
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int min = 1;
int max = 100;
int count = 0;
int randomint = min + (rand() % (int)(max - min + 1));
bool isCorrect = true;
while(!isCorrect){
int guess = 0;
cout << "What is your guess? " << endl;
cin >> guess;
if(guess < randomint){
cout << "Too low!" << endl;
count++;
} else if (guess > randomint){
cout << "Too high!" << endl;
count++;
} else{
cout << "Correct!" << endl;
cout << "Number of Guesses: " << count << endl;
isCorrect = true;
}
}
}
New C++ Programming. I couldn't get this to compile one IDEOne because it doesn't have the input system I need to work this program. I have to submit this for a class shortly, but given that my larger disk (where all my software was stored) was corrupted last night.
I apologize for the silliness of this question.
Yes, it is syntactically correct, but not logically, due to
bool isCorrect = true;
which prevents loop from starting, it should be
bool isCorrect = false;
and works like a charm (but it would be reasonable to initialize the random number generator by for example running srand(time(NULL));)
There are two things logically wrong in your program:
The game won't run at all, since isCorrect is initially true.
The random number generator doesn't get a seed, so rand() will return the same value on every run and randomint is always the same. You should call srand( seed ) beforehand, where seed is a unsigned (for example time(0)).*
*actually, your game will still run if you don't do this, but it's easy to beat after the first try