Writing rand() results to text file in C++ without repeating numbers - c++

At this point in my program, I am writing for every time a random number is generated, the contents of that number in an array is written to a text file. The code:
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include "inFrench.h"
using namespace std;
class student
{
int m_studentNumber;
public:
string nameFirst;
string nameLast;
string nameFull;
int getStudentNumber() { return m_studentNumber; }
void setStudentNumber(int studentNumber) { m_studentNumber = studentNumber; }
};
ostream& operator<<(ostream& os, const student& s)
{
return os << s.nameFirst << ' ' << s.nameLast;
}
student typeName()
{
student bar;
cout << "Type in a student's first name: ";
cin >> bar.nameFirst;
cout << "Type in that student's last name: ";
cin >> bar.nameLast;
bar.nameFull = bar.nameFirst + " " + bar.nameLast;
return bar;
}
void displayStudents(student listOfStudents[50], int studentHeadCount)
{
for (int i = 0; i < studentHeadCount; i++)
{
cout << listOfStudents[i].nameFull << endl;
cout << listOfStudents[i].getStudentNumber() << endl;
cout << "\n";
}
}
void generateGroups(int numberOfGroups, int maxStudents, int studentsPerGroup, int remainder, student theStudents[], int studentsBeenAssigned, ofstream studentGroups)
{
int k;
numberOfGroups = maxStudents / studentsPerGroup;
cout << numberOfGroups << endl;
srand(time(NULL));
studentGroups.open("studentGroups.txt");
while (studentsBeenAssigned < maxStudents && studentsBeenAssigned < maxStudents - remainder)
{
for (int j = 0; j < maxStudents - remainder; j++)
{
k = rand() % maxStudents;
cout << theStudents[k].nameFull << endl;
studentGroups << theStudents[k].nameFull << endl;
studentsBeenAssigned++;
if (studentsBeenAssigned == studentsPerGroup)
{
cout << "\n";
studentGroups << theStudents[k].nameFull << endl;
studentsBeenAssigned = 0;
}
}
}
if (remainder < studentsPerGroup && remainder > 0)
{
for (int l = 0; l < remainder; l++)
{
cout << theStudents[k].nameFull << endl;
}
}
}
void languageChoices()
{
cout << "Select your language from the following:\n";
cout << "a) English\n";
cout << "b) French\n";
cout << "\n";
}
void options()
{
cout << "Select what you want to do:\n";
cout << "1) Exit application\n";
cout << "2) Enter a Student\n";
cout << "3) Display Students\n";
cout << "4) Display Groups\n";
cout << "5) Output groups as text file\n";
cout << "6) Reset number of students in class\n";
cout << "7) Reset number of students per group\n";
cout << "\n";
}
int main()
{
char selectedLanguage;
languageChoices();
cin >> selectedLanguage;
switch (selectedLanguage)
{
case 'a':
{
student allStudents[50]; // Having 50 students alone is ridiculous!
bool endProg = 0;
int maxStudents;
int studentsPerGroup;
int optionSelect;
int studentHeadCount = 0;
int remainder = 0;
int numberOfGroups = 0;
int studentsBeenAssigned = 0;
ofstream studentGroups;
cout << "GroupPicker 1.0\n";
cout << "Note: This version of the program is intended for purposes of education only, "
<< "specifically for teacher use in a classroom.\n\n";
cout << "How many students are in the class?\n" << "(Note: You cannot have more than 50 in this program)\n";
cin >> maxStudents;
if (maxStudents > 50)
{
cerr << "Too many students!\n" << "Exiting program...\n";
system("PAUSE");
exit(1);
}
if (maxStudents >= 35 && maxStudents <= 50)
{
cout << maxStudents << " students? You are a pro!\n";
}
cout << "How many students per group?\n";
cin >> studentsPerGroup;
if (studentsPerGroup >= maxStudents || studentsPerGroup <= 1)
{
cerr << "You're kidding, right?\n" << "Exiting program...\n";
system("PAUSE");
exit(1);
}
while (endProg == 0) {
options();
cin >> optionSelect;
switch (optionSelect) {
case 1:
endProg = 1;
break;
case 2:
{
if (studentHeadCount == maxStudents)
{
cerr << "You can't enter more than " << maxStudents << " students\n";
}
else
{
allStudents[studentHeadCount] = typeName();
allStudents[studentHeadCount].setStudentNumber(studentHeadCount);
cout << "Student (" << allStudents[studentHeadCount].nameFull << ") entered.\n";
cout << "\n";
studentHeadCount++;
}
break;
}
case 3:
cout << "Current list of students:\n\n";
displayStudents(allStudents, studentHeadCount);
break;
case 4:
{
if (studentHeadCount < studentsPerGroup || studentHeadCount < maxStudents)
{
cerr << "Invalid group parameters.\n" << "Returning to main menu...\n\n";
break;
}
else
{
cout << "Here are the groups:\n\n";
studentGroups.open("studentGroups.txt");
generateGroups(numberOfGroups, maxStudents, studentsPerGroup, remainder, allStudents, studentsBeenAssigned, studentGroups);
}
break;
}
case 5:
{
cout << "Saving groups to file...\n";
studentGroups.close();
break;
}
case 6:
{
cout << "How many students are in the class?\n" << "(Note: You cannot have more than 50 in this program)\n";
cin >> maxStudents;
if (maxStudents > 50)
{
cerr << "Too many students!\n" << "Try again...\n";
}
if (maxStudents >= 35 && maxStudents <= 50)
{
cout << maxStudents << " students? You are a pro!\n";
}
break;
}
case 7:
{
cout << "How many students per group?\n";
cin >> studentsPerGroup;
if (studentsPerGroup >= maxStudents || studentsPerGroup <= 1)
{
cerr << "You're kidding, right?\n" << "Try again...\n";
}
break;
}
}
}
break;
}
case 'b':
{
mainInFrench();
}
}
}
When I compile, I get the following errors:
error C2248: 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream' : cannot access private member declared in class 'std::basic_ofstream<_Elem,_Traits>'
IntelliSense: "std::basic_ofstream<_Elem, _Traits>::basic_ofstream(const std::basic_ofstream<_Elem, _Traits>::_Myt &_Right) [with _Elem=char, _Traits=std::char_traits<char>]" (declared at line 1034 of "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\fstream") is inaccessible
How do I resolve these issues (Both on Line 181) and make sure that no number is generated more than once?

std::ofstream cannot be copied. It looks like you need a reference:
void generateGroups(int numberOfGroups, int maxStudents,
int studentsPerGroup, int remainder,
student theStudents[], int studentsBeenAssigned,
ofstream& studentGroups)
{// ^

You are passing stream by value to generateGroups() function which results in copy constructor call. Standard streams cannot be copied.
As for the second part of your question, you cannot expect PRNG to always return unique numbers, let alone when you limit the range with modulus. You'll need to write a bit more code which would check if the number you've got was already generated before, or in other words that some student has already been assigned.

The seed used by rand() won't repeat until 2^32 cycles or more on most implementations, but (seed>>xx)%n will repeat at least every n cycles and more frequently if n is not relatively prime to the numbers used by the linear congruential generator used by rand().
You could make an array of n bytes and use them to track if there's been a duplicate.

Related

Display Array User Input from Function

This is my code at the moment. It is a lottery game and I get user input for 7 numbers and do not allow duplicates (same goes with the random generated). I need to display the user's numbers and the winning random numbers at the end of the main next to LOTTO RESULTS and WINNING NUMBERS.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void getLottoPicks(int userNums[], int size);
void genWinNums(int winNums[], int size);
int main()
{
const int size = 7;
int UserTicket[size];
int WinningNums[size];
char selection;
string name;
do
{
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "q) Quit Program" << endl;
cout << "Please make a selection : " << endl;
cin >> selection;
if (selection == '1')
{
cout << "Please enter your name: " << endl;
cin.ignore();
getline(cin, name);
getLottoPicks(UserTicket, size);
genWinNums(WinningNums, size);
cout << name << "'s LOTTO RESULTS" << endl;
cout << "----------------------" << endl;
cout << "WINNING TICKET NUMBERS : " << endl;
cout << name << "'s TICKET : " << endl;
}
else if (selection == 'q')
{
cout << "You have chosen to quit the program. Thank you for using!" << endl;
}
else
{
cout << "Invalid selection. Please try again." << endl;
}
} while (selection != 'q');
return 0;
}
void getLottoPicks(int userNums[], int size)
{
for (int times = 0; times < size; times++)
{
int input;
cout << "selection #" << times + 1 << ": " << endl;
cin >> input;
bool isNotDuplicate = true;
for (int i = 0; i < times; i++)
{
if (userNums[i] == input)
{
isNotDuplicate = false;
}
}
if (isNotDuplicate == true)
{
userNums[times] = input;
}
else
{
cout << "You already picked this number. Please enter a different number: " <<
endl;
times--;
}
}
}
void genWinNums(int winNums[], int size)
{
srand((unsigned int)time(NULL));
for (int times = 0; times < size; times++)
{
int i;
bool isNotDuplicate = true;
while (isNotDuplicate)
{
isNotDuplicate = false;
i = 1 + rand() % 40;
for (int j = 0; j < times; j++)
{
if (i == winNums[j])
{
isNotDuplicate = true;
}
}
}
winNums[times] = i;
}
}
It seems you might be new to programming so here you go, your working program:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void getLottoPicks(int userNums[], int size);
void genWinNums(int winNums[], int size);
int main()
{
const int size = 7;
int UserTicket[size];
int WinningNums[size];
char selection;
string name;
do
{
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "q) Quit Program" << endl;
cout << "Please make a selection : " << endl;
cin >> selection;
if (selection == '1')
{
cout << "Please enter your name: " << endl;
cin.ignore();
getline(cin, name);
getLottoPicks(UserTicket, size);
genWinNums(WinningNums, size);
cout << name << "'s LOTTO RESULTS" << endl;
cout << "----------------------" << endl;
cout << "WINNING TICKET NUMBERS : " << endl;
for(int i = 0; i < size; i++){
cout << WinningNums[i] << " ";
}
cout << endl;
cout << name << "'s TICKET : " << endl;
for(int i = 0; i < size; i++){
cout << UserTicket[i] << " ";
}
cout << endl;
}
else if (selection == 'q')
{
cout << "You have chosen to quit the program. Thank you for using!" << endl;
}
else
{
cout << "Invalid selection. Please try again." << endl;
}
} while (selection != 'q');
return 0;
}
void getLottoPicks(int userNums[], int size)
{
for (int times = 0; times < size; times++)
{
int input;
cout << "selection #" << times + 1 << ": " << endl;
cin >> input;
bool isNotDuplicate = true;
for (int i = 0; i < times; i++)
{
if (userNums[i] == input)
{
isNotDuplicate = false;
}
}
if (isNotDuplicate == true)
{
userNums[times] = input;
}
else
{
cout << "You already picked this number. Please enter a different number: " <<
endl;
times--;
}
}
}
void genWinNums(int winNums[], int size)
{
srand((unsigned int)time(NULL));
for (int times = 0; times < size; times++)
{
int i;
bool isNotDuplicate = true;
while (isNotDuplicate)
{
isNotDuplicate = false;
i = 1 + rand() % 40;
for (int j = 0; j < times; j++)
{
if (i == winNums[j])
{
isNotDuplicate = true;
}
}
}
winNums[times] = i;
}
}
As you can see, it is pretty easy to loop through an array. Maybe have a look at this for more info on arrays.
Most of the examples show "classic" C++, instead of the more modern variants.
So here's my take on your code :
#include <algorithm>
#include <array>
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
// compile time constant, in many C++ examples this is done with a #define/MACRO
constexpr int number_of_lotto_numbers = 7;
constexpr char play_lotto_char = '1';
constexpr char quit_lotto_char = 'q';
// use std::array instead of int values[]; since this has automatic bound checking!
// no reading/writing beyond array limits is allowed
// I use, using here to make code a bit more readable further down the line
// it lets code show intent instead of implementation
using lotto_numbers_t = std::array<int, number_of_lotto_numbers>;
// do not return arrays by passing arguments, just return an array
// don't worry about this making extra (class) copies c++ knows how to optimize this
lotto_numbers_t get_lotto_picks()
{
lotto_numbers_t lotto_numbers;
auto lotto_numbers_entered{ 0 };
while ( lotto_numbers_entered < number_of_lotto_numbers )
{
int input{ 0 };
std::cout << "selection #" << lotto_numbers_entered + 1 << ": " << std::endl;
std::cin >> input;
// use std::find for finding items in collections, if it finds the end of a collection then
// the value is not found.
if (std::find(lotto_numbers.begin(), lotto_numbers.end(), input) == lotto_numbers.end())
{
// lotto number not found so add it
lotto_numbers[lotto_numbers_entered] = input;
lotto_numbers_entered++;
}
else
{
// lotto number already in array so do not add it but give a message
std::cout << "You already entered this number, try another number" << std::endl;
}
}
return lotto_numbers;
}
lotto_numbers_t generate_winning_numbers()
{
lotto_numbers_t lotto_numbers;
auto lotto_numbers_generated{ 0 };
std::srand((unsigned int)time(NULL));
do
{
int new_number = (std::rand() % 40) + 1;
if (std::find(lotto_numbers.begin(), lotto_numbers.end(), new_number) == lotto_numbers.end())
{
// number not yet found
lotto_numbers[lotto_numbers_generated] = new_number;
lotto_numbers_generated++;
}
} while (lotto_numbers_generated < number_of_lotto_numbers);
return lotto_numbers;
}
void play_lotto()
{
char selection{ 0 }; // always initialize variables!
std::string name;
do
{
std::cout << "LITTLETON CITY LOTTO MODEL: " << std::endl;
std::cout << "---------------------------" << std::endl;
std::cout << "1) Play Lotto" << std::endl;
std::cout << "q) Quit Program" << std::endl;
std::cout << "Please make a selection : " << std::endl;
std::cin >> selection;
if (selection == play_lotto_char)
{
std::cout << "Please enter your name: " << std::endl;
std::cin.ignore();
std::getline(std::cin, name);
auto picked_numbers = get_lotto_picks();
auto winning_numbers = generate_winning_numbers();
std::cout << name << "'s LOTTO RESULTS" << std::endl;
std::cout << "----------------------" << std::endl;
std::cout << "WINNING TICKET NUMBERS : " << std::endl;
for (const auto number : winning_numbers)
{
std::cout << number << " ";
}
std::cout << std::endl;
std::cout << name << "'s TICKET : " << std::endl;
for (const auto number : picked_numbers)
{
std::cout << number << " ";
}
std::cout << std::endl;
if (picked_numbers == winning_numbers)
{
std::cout << "you have won!" << std::endl;
}
}
else if (selection == quit_lotto_char)
{
std::cout << "You have chosen to quit the program. Thank you for using!" << std::endl;
}
else
{
std::cout << "Invalid selection. Please try again." << std::endl;
}
} while (selection != quit_lotto_char);
}
Don't hesitate to ask questions on this code if you have any :)

Hangman only gets first letter of secret word

I am trying to write a hangman program for an assignment. I've written code I thought would work, yet when testing it with the secret word, "IMPOSSIBLE", it only reads the "I" and nothing else. I tried changing all my strings to character lists but I don't think that was the issue. Does anyone have any advice on what I am doing incorrectly?
Thanks,
Keith.
Here is the code:
/* CSCI 261 Assignment 5: Hang Man Game
*
* Author: Keith Danielson
*
* A program that runs a simple hang man game
*/
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
//const string SECRET_WORD = "IMPOSSIBLE";
int main() {
const char SECRET_WORD[10] = {'I','M','P','O','S','S','I','B','L','E'};
const int SECRET_WORD_LENGTH = 10;
//Defining the number of wrong guesses available, found letters, wrong guesses, and user choice.
int guesses = 7;
char foundLetters[SECRET_WORD_LENGTH];
char wrongGuesses[guesses];
char userChoice;
//Filling foundLetters with underslashes based on the length of the secret word.
for (int i = 0; i <= SECRET_WORD_LENGTH; i++) {
foundLetters[i] = '_';
}
cout << "Welcome to hangman!" << endl;
for (int i = 0; i <= 7; i++) {
if (guesses == 0){
break;
}
cout << "Take a guess: ";
for (int j = 0; j <= SECRET_WORD_LENGTH; j++) {
cout << foundLetters[j] << " ";
}
cout << "\n" << "Your guess: ";
cin >> userChoice;
//if the user input is lowercase it'll be made upper case.
if (islower(userChoice)) {
userChoice = toupper(userChoice);
}
for (int j = 0; j <= SECRET_WORD_LENGTH; j++) {
//if (userChoice == foundLetters[j]) {
// cout << "You already guessed" << userChoice << "." << endl;
// break;
//}
if (userChoice == SECRET_WORD[j]) {
cout << "There's a " << userChoice << "!" << endl;
foundLetters[j] = userChoice;
break;
}
else if (userChoice != SECRET_WORD[j]) {
guesses = guesses - 1;
cout << "Sorry. No " << userChoice << "'s." << endl;
wrongGuesses[i] = userChoice;
if (guesses == 0) {
cout << "You lose! Try again.";
break;
}
else {
cout << "You have " << guesses << " remaining." << endl;
break;
}
}
}
}
return 0; // signals the operating system that our program ended OK.
}
Try something more like this instead:
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
#include <limits>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
const char SECRET_WORD[10] = {'I','M','P','O','S','S','I','B','L','E'};
const int SECRET_WORD_LENGTH = 10;
//Defining the number of wrong guesses available
const int WRONG_GUESSES = 7;
bool hasLetter(const char *letters, int numLetters, char ch) {
for (int i = 0; i < numLetters; ++i) {
if (letters[i] == ch) {
return true;
}
}
return false;
}
int main() {
char foundLetters[SECRET_WORD_LENGTH];
int foundLetters = 0;
char wrongLetters[WRONG_GUESSES];
int wrongLettersLength = 0;
int wrongGuessesLeft = WRONG_GUESSES;
char userChoice;
int found;
//Filling foundLetters with underslashes based on the length of the secret word.
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
foundLetters[j] = '_';
}
cout << "Welcome to hangman!" << endl;
while (true) {
cout << "Take a guess: ";
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
cout << foundLetters[j] << " ";
}
cout << "\n";
cout << "Your guess: ";
cin >> userChoice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//if the user input is lowercase it'll be made upper case.
userChoice = toupper(userChoice);
if (hasLetter(foundLetters, SECRET_WORD_LENGTH, userChoice) ||
hasLetter(wrongGuesses, wrongGuessesLength, userChoice))
{
cout << "You already guessed " << userChoice << "." << endl;
continue;
}
found = 0;
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
if (SECRET_WORD[j] == userChoice) {
foundLetters[j] = userChoice;
++found;
}
}
if (found > 0) {
cout << "There's " << found << " " << userChoice << (found > 1 ? "'s" : "") << "!" << endl;
foundLettersLength += found;
if (foundLettersLength == SECRET_WORD_LENGTH) {
cout << "You win!";
break;
}
}
else {
cout << "Sorry. No " << userChoice << "'s." << endl;
wrongLetters[wrongLettersLength++] = userChoice;
if (--wrongGuessesLeft == 0) {
cout << "You lose! Try again.";
break;
}
cout << "You have " << wrongGuessesLeft << " guess" << (wrongGuessesLeft > 1 ? "es" : "") << " remaining." << endl;
}
}
return 0; // signals the operating system that our program ended OK.
}
Alternatively:
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
#include <limits>
#include <set>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
const string SECRET_WORD = "IMPOSSIBLE";
//Defining the number of wrong guesses available
const int WRONG_GUESSES = 7;
int main() {
//Filling foundLetters with underslashes based on the length of the secret word.
string foundLetters(SECRET_WORD.size(), '_');
set<char> guessedLetters;
int wrongGuessesLeft = WRONG_GUESSES;
char userChoice;
int found;
cout << "Welcome to hangman!" << endl;
while (true) {
cout << "Take a guess: ";
for (int j = 0; j < foundLetters.size(); ++j) {
cout << foundLetters[j] << " ";
}
cout << "\n";
cout << "Your guess: ";
cin >> userChoice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//if the user input is lowercase it'll be made upper case.
userChoice = toupper(userChoice);
if (!guessedLetters.insert(userChoice).second)
{
cout << "You already guessed " << userChoice << "." << endl;
continue;
}
string::size_type pos = SECRET_WORD.find(userChoice);
if (pos != string::npos) {
found = 0;
do {
foundLetters[pos] = userChoice;
++found;
pos = SECRET_WORD.find(userChoice, pos+1);
}
while (pos != string::npos);
cout << "There's " << found << " " << userChoice << (found > 1 ? "'s" : "") << "!" << endl;
if (foundLetters == SECRET_WORD) {
cout << "You win!";
break;
}
}
else {
cout << "Sorry. No " << userChoice << "'s." << endl;
if (--wrongGuessesLeft == 0) {
cout << "You lose! Try again.";
break;
}
cout << "You have " << wrongGuessesLeft << " guess" << (wrongGuessesLeft > 1 ? "es" : "") << " remaining." << endl;
}
}
return 0; // signals the operating system that our program ended OK.
}

calculating scores and total questions asked

I'm trying to output the score for each addition, subtraction, multiplication, division in the end test function. and the total of the question asked.
**Any help would be appreciated
BTW this is only using local functions and is passing the scores by reference. IT's supposed to output the number of answers that you answer correctly.
Also is there a way where you can prevent the program from letting you select the choices more than once?
here's what I got so far:
#include < iostream >
#include < iomanip >
#include < stdlib.h >
#include < time.h >
#include < stdlib.h >
using namespace std;
int addition(int addscore);
int subtraction(int subscore);
int multiplication(int multiscore);
int division(int divscore);
int endtest(int & addscore, int & subscore, int & multiscore, int & divscore);
main() {
int end_final = 0;
do {
int addscore, subscore, multiscore, divscore;
char choice;
cout << "A- " << "Addition\n";
cout << "B- " << "Subtraction\n";
cout << "C- " << "Multiplication\n";
cout << "D- " << "Division\n";
cout << "E- " << "End of Test\n";
cin >> choice;
cout << endl << endl;
switch (choice) {
case 'A':
case 'a':
addition(addscore);
break;
case 'B':
case 'b':
subtraction(subscore);
break;
case 'C':
case 'c':
multiplication(multiscore);
break;
case 'D':
case 'd':
division(divscore);
break;
case 'E':
case 'e':
endtest(addscore, subscore, multiscore, divscore);
break;
}
}
while (end_final != 1);
return 0;
}
int addition(int addscore) {
int iRandom;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen addition\n";
int randnum1, randnum2;
int total = 0;
for (int i = 1; i <= 5; i++) {
randnum1 = rand() % 15 + 1;
randnum2 = rand() % 15 + 1;
cout << randnum1 << " " << "+" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total++;
if (answer == randnum1 + randnum2) {
cout << "Correct! \n";
addscore++;
} else {
cout << "Incorrect \n";
}
}
}
int subtraction(int subscore) {
int iRandom;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen subtraction\n";
int randnum1, randnum2;
int total = 0;
while (total != 5) {
randnum1 = rand() % 20 + 1;
randnum2 = rand() % 20 + 1;
if (randnum1 >= randnum2) {
cout << randnum1 << " " << "-" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total++;
if (answer == randnum1 - randnum2) {
cout << endl;
cout << "Correct!\n ";
subscore++;
} else {
cout << "Incorrect\n ";
}
}
}
}
int multiplication(int multiscore) {
int iRandom;
int total = 0;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen Multiplication\n";
int randnum1, randnum2;
for (int i = 1; i <= 5; i++) {
randnum1 = rand() % 20 + 1;
randnum2 = rand() % 20 + 1;
cout << randnum1 << " " << "x" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total++;
if (answer == randnum1 * randnum2) {
cout << endl;
cout << "Correct! \n";
multiscore++;
} else {
cout << "Incorrect\n ";
}
}
}
int division(int divscore) {
int iRandom;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen Division\n";
int randnum1, randnum2;
int total = 0;
while (total != 5) {
randnum1 = rand() % 13 + 1;
randnum2 = rand() % 13 + 1;
if (randnum1 % randnum2 == 0) {
cout << randnum1 << " " << "/" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total++;
if (answer == randnum1 / randnum2) {
cout << endl;
cout << "Correct! \n";
divscore++;
} else {
cout << "Incorrect\n ";
}
}
}
}
int endtest(int & addscore, int & subscore, int & multiscore, int & divscore) {
int total = 0;
cout << endl << endl;
cout << "Addition" << " " << addscore++ << endl;
cout << "Subtraction" << " " << subscore << endl;
cout << "Multiplication" << " " << multiscore << endl;
cout << "Division" << " " << divscore << endl;
cout << "Total" << " " << total << endl;
}
To clarify the code, declare an enum
enum { ADDITION=0, SUBTRACTION, MULTIPLICATION, DIVISION };
You could have global arrays
int used[] = { 0,0,0,0 }; // not used
int total[] = { 0,0,0,0 }; // total questions per operation
int score[] = { 0,0,0,0 }; // score per operation
Then, doing it for 'addition', in the do {
if ( ! used[ADDITION]) cout << "A- " << "Addition\n";
then in the switch
case 'A':
case 'a':
used[ADDITION] = 1; // tells addition was used
addition(addscore);
break;
The addition code becomes
int addition(int addscore) {
int iRandom;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen addition\n";
int randnum1, randnum2;
total[ADDITION] = 0; // should not be
score[ADDITION] = 0; // ...necessary (but in case you call it again)
for (int i = 0; i < 5 ; i++) {
randnum1 = rand() % 15 + 1;
randnum2 = rand() % 15 + 1;
cout << randnum1 << " " << "+" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total[ADDITION]++; // total is incremented for Addition
if (answer == randnum1 + randnum2) {
cout << "Correct! \n";
score[ADDITION]++; // score is incremented
} else {
cout << "Incorrect \n";
}
}
}
endtest becomes
int endtest() {
cout << endl << endl;
if (used[ADDITION]) cout << "Addition" << " " << score[ADDITION] << " / " << total[ADDITION] << endl;
// same for SUBTRACTION ...
int grandtotal = total[ADDITION] + ....;
cout << "Grand Total" << " " << grandtotal << endl;
}
endtest is declared, and called like that
int endtest();
...
endtest();
Since this is C++, you could also make a class Operation, then one subclass per operation, holding the name of the operation and overriding a 'execute' method that does the specific operation, then declare an array of the parent class that holds an instance of each operation ...
Based on OP's comments, after the do {
// initialize variables to zero
int addscore=0, subscore=0, multiscore=0, divscore=0;
in the switch
case 'A':
case 'a':
used[ADDITION] = 1; // tells addition was used
addition( &addscore ); // <== gives the pointer to that variable
break;
then in addition code
int addition(int *addscore) { // <== gets a pointer
int iRandom;
// initialize random seed:
srand(time(NULL));
int answer;
cout << "You have chosen addition\n";
int randnum1, randnum2;
total[ADDITION] = 0; //
score[ADDITION] = 0; // using your way, this is not necessary anymore
for (int i = 0; i < 5 ; i++) {
randnum1 = rand() % 15 + 1;
randnum2 = rand() % 15 + 1;
cout << randnum1 << " " << "+" << " " << randnum2 << " " << "= ";
cin >> answer;
cin.ignore(80, '\n');
total[ADDITION]++; // total is incremented for Addition
if (answer == randnum1 + randnum2) {
cout << "Correct! \n";
// score[ADDITION]++; // score is incremented (see above)
*addscore++; // <== increment variable pointed to by pointer
} else {
cout << "Incorrect \n";
}
}
}

How do I sort,search, and get get the sum and average in an array

For my code I need to search for the largest number in the array, add up and get the averages of the numbers inside of it, and search for the largest number in it. my code has the basic idea of what i want to do for each.
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include<fstream>
using namespace std;
void menu();
string createFile();
void displayNumTotalAverage(string);
void displaySortedNums();
void BubbleSort();
void SearchNum();
void displayLargestNum();
void appendRandomNum(string);
void exit();
void CreateFile();
void printFunc(int[]);
void fillFunc(int[]);
int main()
{
menu();
string FileName;
createFile();
CreateFile();
system("pause");
return 0;
}
void menu()
{
int choice;
string FileName;
do
{
//program output
cout << "** MENU **" << endl << endl;
cout << "Curret Data File: " << endl << endl;
cout << "(1) Select / create data file (.txt file extention will be added automaticly)" << endl;
cout << "(2) Display all numbers, total and average" << endl;
cout << "(3) Display all numbers sorted" << endl;
cout << "(4) search for a number and display how many times it occurs" << endl;
cout << "(5) display the largest number" << endl;
cout << "(6) Append a random number(s)" << endl;
cout << "(7) Exit the program" << endl << endl;
//user input
cout << "Menu Choice: ";
cin >> choice;
while (choice > 7 || choice < 1)
{
cout << "Menu Choice: ";
cin >> choice;
}
switch (choice)
{
case 1:
cout << "\nChoice 1" << endl << endl;
createFile();
break;
case 2:
cout << "\nChoice 2" << endl << endl;
displayNumTotalAverage(FileName.c_str());
break;
case 3:
cout << "\nChoice 3" << endl << endl;
break;
case 4:
cout << "\nChoice 4" << endl << endl;
break;
case 5:
cout << "\nChoice 5" << endl << endl;
break;
case 6:
cout << "\nChoice 6" << endl << endl;
appendRandomNum(FileName.c_str());
break;
case 7:
exit();
break;
}
} while (choice != 7);
}
string createFile()
{
string FileName;
ifstream inFile;
cout << "Name of data file: ";
cin >> FileName;
FileName = "C:\\Users\Wizard\Libraries\Documents\Final Project.txt" + FileName;
inFile.open(FileName + ".txt");
if (inFile)
{
cout << FileName;
}
else
cout << "File not found, creating file."<<endl;
system("PAUSE");
return FileName;
}
void displayNumTotalAverage(string FileName)
{
ifstream inFile;
cout << "Display Number Total Average - Option 2" << endl << endl << endl;
inFile.open("C:\\Users\Wizard\Libraries\Documents\Final Project" + FileName + ".txt");
int num;
int total=0;
cout << "Display Number Total Average function" << FileName << endl;
double average;
bool containsNum = false;
inFile.open(FileName + ".txt");
if (inFile)
{
while (inFile >> num)
{
cout << num << endl;
}
inFile.close();
}
else
{
cout << "Error opening file" << FileName << "." << endl;
}
system("PAUSE");
return;
}
void displaySortedNums(int arr[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (arr[count]>arr[count + 1])
{
temp = arr[count];
arr[count] = arr[count + 1];
swap = true;
}
}
} while (swap);
system("PAUSE");
return;
}
void searchNum()
{
cout << " I am the searchNum function - option 4" << endl;
system("PAUSE");
return;
}
void displayLargestNum(int arr[], int numElems, int value)
{
{
int index = 0;
int position = -1;
bool found = false;
while (index < numElems && !found)
{
if (arr[index] == value)
found = true;
position = index;
}
index++;
return;
}
system("PAUSE");
return;
}
void appendRandomNum(string FileName)
{
int num = 0;
int count = 0;
ofstream outFile;
outFile.open(FileName + ".txt", ios::app);
cout << "How many random numbers: ";
cin >> count;
for (int i = 0; i < count; i++)
outFile << rand() % 10 << endl;
outFile.close();
cout << endl << "Number(s) Added" << endl << endl;
system("PAUSE");
return;
}
void exit()
{
std::exit(0);
system("PAUSE");
return;
}
void CreateFile()
{
int random[50]; //Random Numbers
srand((unsigned)time(NULL));
fillFunc(random);
printFunc(random);
return;
}
void fillFunc(int arr[])
{
for (int i = 0; i < 50; i++)
{
arr[i] = 1 + rand() % 10;
}
}
void printFunc(int arr[])
{
ofstream fout("C:\\Users\Wizard\Libraries\Documents\Final Project");
if (fout.is_open()){
for (int i = 0; i < 50; i++)
{
fout << arr[i] << std::endl;
}
}
}
If your array name is arr and size is n.
Search the largest number as follows:
int max = arr[0];
for ( int i = 1; i < n; i++ )
max = (arr[i] > max ) ? arr[i] : max;
Finally, max is the largest number.
To add up the array:
int sum = 0;
for ( int i = 0; i < n; i++ )
sum += arr[i];

Vectors with cout operator issue in C++

In my program, I am encountering an error with trying to print the end() of a vector. Here is the code:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <time.h>
#include "inFrench.h"
using namespace std;
class student
{
int m_studentNumber;
public:
string nameFirst;
string nameLast;
string nameFull;
int getStudentNumber() { return m_studentNumber; }
void setStudentNumber(int studentNumber) { m_studentNumber = studentNumber; }
};
class group
{
public:
vector<student> groupMembers;
};
ostream& operator<<(ostream& os, const student& s)
{
return os << s.nameFirst << ' ' << s.nameLast;
}
student typeName()
{
student bar;
cout << "Type in a student's first name: ";
cin >> bar.nameFirst;
cout << "Type in that student's last name: ";
cin >> bar.nameLast;
bar.nameFull = bar.nameFirst + " " + bar.nameLast;
return bar;
}
void displayStudents(student listOfStudents[50], int studentHeadCount)
{
for (int i = 0; i < studentHeadCount; i++)
{
cout << listOfStudents[i].nameFull << endl;
cout << listOfStudents[i].getStudentNumber() << endl;
cout << "\n";
}
}
void generateGroups(int numberOfGroups, int maxStudents, int studentsPerGroup, int remainder, group foo, student theStudents[], int studentsBeenAssigned)
{
int k;
numberOfGroups = maxStudents / studentsPerGroup;
cout << numberOfGroups << endl;
srand(time(NULL));
while (studentsBeenAssigned << maxStudents)
{
for (int j = 0; j < maxStudents; j++)
{
k = rand() % maxStudents;
foo.groupMembers.push_back(theStudents[k]);
cout << foo.groupMembers.end() << endl;
studentsBeenAssigned++;
}
}
if (remainder < studentsPerGroup && remainder > 0) // Still coding this section
{
foo.groupMembers.push_back(theStudents[k]);
}
}
void languageChoices()
{
cout << "Select your language from the following:\n";
cout << "a) English\n";
cout << "b) French\n";
cout << "\n";
}
void options()
{
cout << "Select what you want to do:\n";
cout << "1) Exit application\n";
cout << "2) Enter a Student\n";
cout << "3) Display Students\n";
cout << "4) Display Groups\n";
cout << "5) Output groups as text file\n";
cout << "\n";
}
int main()
{
char selectedLanguage;
languageChoices();
cin >> selectedLanguage;
switch (selectedLanguage)
{
case 'a':
{
group finishedListOfStudents;
student allStudents[50]; // Having 50 students alone is ridiculous!
bool endProg = 0;
int maxStudents;
int studentsPerGroup;
int optionSelect;
int studentHeadCount = 0;
int remainder = 0;
int numberOfGroups;
int studentsBeenAssigned;
cout << "GroupPicker 1.0\n";
cout << "Note: This version of the program is intended for purposes of education only, "
<< "specifically for teacher use in a classroom.\n\n";
cout << "How many students are in the class?\n" << "(Note: You cannot have more than 50 in this program)\n";
cin >> maxStudents;
if (maxStudents > 50)
{
cerr << "Too many students!\n" << "Exiting program...\n";
system("PAUSE");
exit(1);
}
if (maxStudents >= 35 && maxStudents <= 50)
{
cout << maxStudents << " students? You are a pro!\n";
}
cout << "How many students per group?\n";
cin >> studentsPerGroup;
if (studentsPerGroup >= maxStudents || studentsPerGroup <= 1)
{
cerr << "You're kidding, right?\n" << "Exiting program...\n";
system("PAUSE");
exit(1);
}
while (endProg == 0) {
options();
cin >> optionSelect;
switch (optionSelect) {
case 1:
endProg = 1;
break;
case 2:
{
if (studentHeadCount == maxStudents)
{
cerr << "You can't enter more than " << maxStudents << " students\n";
}
else
{
allStudents[studentHeadCount] = typeName();
allStudents[studentHeadCount].setStudentNumber(studentHeadCount);
cout << "Student (" << allStudents[studentHeadCount].nameFull << ") entered.\n";
cout << "\n";
studentHeadCount++;
}
break;
}
case 3:
cout << "Current list of students:\n\n";
displayStudents(allStudents, studentHeadCount);
break;
case 4:
{
if (studentHeadCount < studentsPerGroup || studentHeadCount < maxStudents)
{
cerr << "Invalid group parameters.\n" << "Returning to main menu...\n\n";
break;
}
else
{
cout << "Here are the groups:\n";
generateGroups(numberOfGroups, maxStudents, studentsPerGroup, remainder, finishedListOfStudents, allStudents, studentsBeenAssigned);
}
break;
}
case 5:
{
cout << "Saving groups to file...\n";
ofstream studentGroups;
studentGroups.open("studentGroups.txt");
break;
}
}
}
break;
}
case 'b':
{
mainInFrench();
}
}
}
I get the following results:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::_Vector_iterator<_Myvec>' (or there is no acceptable conversion) [Line 66]
IntelliSense: no operator "<<" matches these operands. operand types are: std::ostream << std::_Vector_iterator<std::_Vector_val<std::_Simple_types<student>>> [Line 66]
I have considered overloading the ostream operator<< operator again, but is there another option?
std::vector::end() returns an iterator to the end of the vector , not the actual last element.
You could print the last item like this instead:
cout << foo.groupMembers.at(foo.groupMembers.size() - 1);
Turns out, I never needed the vector in the first place. I just had to use the arrays. I have answered my own question.