Adding a time delay to simulate lottery numbers being drawn - c++

new to the forums here and beginning to learn C++. This site has already helped me so much with syntax and other things. What I'm trying to do with my code is have the number print to screen, have the time delay, then print the next number. Currently the time delay works, but it prints all 13 numbers generated. Any ideas of what I'm doing wrong?
Here's my code:
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <windows.h>
using namespace std;
int main( )
{
// Function prototypes
int random ( int minValue, int maxValue);
// Constant declarations
const int maxValue = 9;
const int minValue = 0;
// Local variable declarations
int seed;
int numberOfPeople;
int peopleCount = 0;
int numberCount;
int number;
// Initialize the random number generator
cout << "Welcome to the Lottery!" << endl;
cout << "Enter your lucky number to start: " << endl;
cin >> seed;
srand (seed);
// Generate and display numbers
cout << "Enter the number of people participating in the lottery:" << endl;
cin >> numberOfPeople;
cout << "Your lucky lottery numbers for the day are:" << endl;
cout.setf (ios::left, ios::adjustfield);
cout << setw(8) << "Pick 3" << setw(10) << "Pick 4" <<
setw(15) << "Pick 6" << endl;
while (peopleCount < numberOfPeople) {
numberCount = 0;
while (numberCount < 13){
number = random (minValue, maxValue);
Sleep (500); // pauses for half a second
cout << number << " ";
if (numberCount == 2){
cout << " "; }
else if (numberCount == 6){
cout << " "; }
else if (numberCount == 12){
cout << endl; } //end if, else if
numberCount++;
} //end nested while
peopleCount++;
} // end while
return 0;
} // end main()
/**
* Produces a pseudo-random number
* #param minValue minimum value that can be generated
* #param maxValue maximum value that can be generated
*
* #return psuedo-random number in the specified range
*/
int random ( int minValue, // min possible number to be generated
int maxValue) // max possible number to be generated
{
return ( (rand() % maxValue) + minValue);
} // end random()

cout is generally buffered, and the newline causes the buffer to be flushed to the screen. As you display the numbers on the same line, this could explain that everything is displayed at onece despite the delay that you've build in.
Use cout.flush(); to force output to be done without buffering delay. You could as well use the manipulator form: cout << number << " " << flush;

Related

How to code in C++ mutiple return values to main from mutiple modules and display each modules totals?

I must write a program where the user can choose to practice with topic addition or topic multiplication that starts with a self-driven menu.
It must keep track of questions answered right, wrong and the number of questioned asked.
Which my current program is doing within each module(topic). Example Addition keeps track of the questions while the user is practicing Addition only and Multiplication does the same.
However, they are not being feedback to main, so they are not being added or displayed before the user can select another topic to practice or to exit the program.
Currently it is only to keeping track of the question (right /wrong/ total of questions) for each module (topic).
My goal is for the values to be passed to main and display the total number (right /wrong/ total of questions) before the user exits the program, but at the same time I must display the number of question in the Additional Topic and the Multiplication topic and provide a total.
Example Table of Addition, Multiplication and Totals ?
This is the code I have to start with. Can someone help me in how to code to return values of the (right /wrong/ total of questions) of the two topics and accomplish to display something like the table information.
******************************************************************************* /
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <string> // String managment funtions.
#include <iostream> // For input and output
#include <cmath> // For math functions.
#include <math.h>
#include <cstdlib>
using namespace std;
////////////////////////////////////////////////////////////////////////
// Implementing menu driven programs.
// Function Prototypes.
int menu();
void sums();
void products();
int main()
{
srand(time(0));
int option;
do {
option = menu();
switch (option) {
case 1: {
sums();
break;
}
case 2: {
products();
break;
}
default:
cout << "Program exit" << endl;
}
} while (option != 6);
return 0;
}
int menu()
{
cout << "Please select an option" << endl;
cout << "1) Practice with Addition " << endl;
cout << "2) Pratice with Multiplication " << endl;
cout << "3) Exit the program " << endl;
int option;
cin >> option;
return option;
}
void sums()
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValue = 10;
const int maxValue = 99;
int y = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is x "<< x << endl;
cout << "What is " << x << " + " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x + y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
void products()
{
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValueOne = 0;
const int maxValueOne = 9;
const int minValueTwo = 10;
const int maxValueTwo = 99;
int y = (rand() % (maxValueOne - minValueOne + 1)) + minValueOne;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValueTwo - minValueTwo + 1)) + minValueTwo;
// cout<< " the random number is x "<< x << endl;
cout << " What is " << x << " x " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x * y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
}
I would create a structure that contains the number of total answers and number of correct answers—the incorrect ones can be inferred—and then pass a reference to an instance of the structure to the respective sums() and products() functions.
Those functions can then populate the structure elements and when they return, your main function can read them out, knowing exactly how many questions were asked, how many were answered, or whatever other information you want to record and retrieve.

How would I calcuate the total of all the items entered to then calculate the total price?

Hi there apologise if my question is poorly worded, I'm struggling to find a solution to my problem.
The purpose of my program is to allow the user to enter predefined bar codes that associate with items and a price. The user enters as many barcodes as they want, and when they're done they can exit the loop by pressing "F" and then total price for all the items is displayed.
This is my code so far, I'm very new to programming..
#include <iostream>
#include <iomanip>
using namespace std;
int index_of(int arr[], int item, int n) {
int i = 0;
while (i < n) {
if(arr[i] == item) {
return i;
}
i++;
}
return -1;
}
const int SIZE = 10;
int main()
{
string item [SIZE] = {"Milk", "Bread", "Chocolate", "Towel", "Toothpaste", "Soap", "Pen", "Biscuits", "Lamp", "Battery"};
int barcode [SIZE] = {120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009, 120010};
float price [SIZE] = {10.50, 5.50, 8.00, 12.10, 6.75, 5.20, 2.00, 4.45, 20.50, 10.00};
cout << "*************************************************************" << endl;
cout << "WELCOME TO THE CHECKOUT SYSTEM" << endl;
cout << "Please scan a barcode or manually enter the barcode ID number" << endl;
cout << "*************************************************************\n" << endl;
int newBarcode;
while (true){
cout << "Please enter a barcode (Type 'F' to finish): ", cin >> newBarcode;
int index = index_of(barcode, newBarcode, (sizeof(barcode) / sizeof(barcode)[0]));
cout << "\n>> Name of item: " << item[index] << endl;
cout << ">> Price of item: \x9C" << setprecision (4)<< price[index] << endl;
cout << ">> " <<item[index] << " has been added to your basket. \n" << endl;
float total = 0 + price[index];
cout << ">> Your current basket total is: \x9C" << setprecision(4) << total << endl;
/*float total = 0;
float newtotal = 0;
price[index] = total;
total = newtotal;
cout << ">> " << "Basket total: " << newtotal << endl; */
}
return 0;
}
You will need to iterate over all items and add their value to a variable. You can do it the old way:
float sum = 0;
for(int i = 0; i < SIZE; i++) {
sum += price [i];
}
Or the C++11 way:
float sum = 0;
for(float p : price) {
sum += p;
}
However I must point out a few important issues with your code:
Your array has a fixed size but user can enter as many entries as he wants. To avoid this issue, use vector. It behaves like array but has dynamic size. Simply use push_back() to add a new element.
Don't use separate containers (arrays) for the same group of objects. It's a bad coding practice. You can define a structure for product which will contain name, barcode and price, then make one container for all of the products.
Edit
I'm sorry, I misunderstood your problem. There are many ways to solve this, the most elegant way is to create a map where key is the bar code and value is your product object or just a price.
map<int, float> priceMap;
priceMap.insert(pair<int, float>([your bar code here], [your price here]))
Afterwards just create a vector of bar codes, fill it with user data and iterate over it sum all prices:
float sum = 0;
for(int b : userBarcodes) {
sum += priceMap.at(b);
}
You are trying to read from cin into an int. As you decide to put a stopping condition on 'F' input you must read into a string. Then decide what to do with the value. You will need to check if the input is an int or not. You can do it as given here or here.
Or you may change the stopping condition to a less likely integer like -1. And make sure you always read an int into newBarcode.
There are various small errors which are hard to list out. I have changed them in the code below which is implementing point 2 (You have to add the stopping condition).
One of the error or wrong practice is to declare new variables inside a loop. In most cases you can declare the variables outside and change there values in the loop.
I replaced (sizeof(barcode) / sizeof(barcode)[0] with SIZE as the lists are predefined and unchanging. Anyways you should use (sizeof(barcode) / sizeof(barcode[0]) for length calculation.
#include <iostream>
#include <iomanip>
using namespace std;
int index_of(int arr[], int item, int n) {
int i = 0;
while (i < n) {
if(arr[i] == item) {
return i;
}
i++;
}
return -1;
}
const int SIZE = 10;
int main()
{
string item [SIZE] = {"Milk", "Bread", "Chocolate", "Towel", "Toothpaste", "Soap", "Pen", "Biscuits", "Lamp", "Battery"};
int barcode [SIZE] = {120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009, 120010};
float price [SIZE] = {10.50, 5.50, 8.00, 12.10, 6.75, 5.20, 2.00, 4.45, 20.50, 10.00};
cout << "*************************************************************" << endl;
cout << "WELCOME TO THE CHECKOUT SYSTEM" << endl;
cout << "Please scan a barcode or manually enter the barcode ID number" << endl;
cout << "*************************************************************\n" << endl;
int newBarcode;
float total = 0;
int index;
while (true){
cout << "Please enter a barcode (Type -1 to finish): \n";
cin >> newBarcode;
while(cin.fail()) {
cout << "Not an integer" << endl;
cin.clear();
cin.ignore(100,'\n');
cin >> newBarcode;
}
index = index_of(barcode, newBarcode, SIZE);
cout << index;
if (index == -1) {
cout << "Apologies here for unsupported barcode\n";
continue;
} else {
cout << ">> Name of item: " << item[index] << endl;
cout << ">> Price of item: " << price[index] << "\n";
cout << ">> " <<item[index] << " has been added to your basket. \n";
total = total + price[index];
cout << ">> Your current basket total is: " << total << "\n";
}
}
return 0;
}
Your question could be more helpful to others if you find out what is wrong with your implementation and ask implementation specific questions which will probably be already answered. Asking what is wrong with my code is not quite specific.

Using a number to quit a program in c++ while not evaluating the actual number [closed]

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 5 years ago.
Improve this question
I am attempting to create a loop that allows a user to input an integer until they quit the program using the number -99. The program is suppose to then print the largest and smallest number to the screen, but it keeps saying that my smallest number is -99.
Here is the code I have so far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Initialize integers for use
long int number, largest, smallest;
// Set condition for user input
while (number != -99)
{
// Allow user to input numbers to test
cout << " Enter a number to find the smallest and largest integer. " << endl;
cout << " Enter -99 to quit " << endl;
cin >> number;
// Evaluate user input
if (number < smallest)
{
smallest = number;
}
if (number > largest)
{
largest = number;
}
}
cout << " The smallest number you entered was " << smallest << endl;
cout << " The largest number you entered was " << largest << endl;
return 0;
}
Check the number immediately after reading it, and break out of the loop then, instead of using it to update smallest and largest.
You also need to initialize smallest and largest before you can compare them with new numbers. I've done that below by treating the first iteration of the loop specially (with the first_time variable).
#include <iostream>
using namespace std;
int main()
{
//Initialize integers for use
long int number, largest, smallest;
bool first_time = true;
// Set condition for user input
while (true)
{
// Allow user to input numbers to test
cout << " Enter a number to find the smallest and largest integer. " << endl;
cout << " Enter -99 to quit " << endl;
cin >> number;
if (number == -99) {
break;
}
// Evaluate user input
if (first_time) {
smallest = largest = number;
first_time = false;
} else if (number < smallest)
{
smallest = number;
} else if (number > largest)
{
largest = number;
}
}
if (!first_time) {
cout << " The smallest number you entered was " << smallest << endl;
cout << " The largest number you entered was " << largest << endl;
}
return 0;
}
Try this code:
#include <iostream>
using namespace std;
int main()
{
bool isInitialised = false;
//Initialize integers for use
long int number, largest, smallest;
// Set condition for user input
while (true)
{
// Allow user to input numbers to test
cout << " Enter a number to find the smallest and largest integer. " << endl;
cout << " Enter -99 to quit " << endl;
cin >> number;
// if number is -99, break loop
if (number == -99) {
break;
}
// Evaluate user input
if (!isInitialised) {
isInitialised = true;
smallest = number;
largest = number;
// after first input no need to make comparisons.
continue;
}
if (number < smallest)
{
smallest = number;
}
else if (number > largest)
{
largest = number;
}
}
cout << " The smallest number you entered was " << smallest << endl;
cout << " The largest number you entered was " << largest << endl;
return 0;
}
It's surprisingly tricky to get right.
SPOILER ALERT and WARNING...
If you read this before finishing the assignment, you will not suffer the pain and humiliation that the instructor wants you to. And he/she will know it's not your work. (I just thought of a way to make it look even slicker, but this is slick enough for now.)
#include <iostream>
#include <numeric>
#include <algorithm>
using namespace std; // Forgive me, for I have sinned.
using int_t = long int;
int_t get_number(int_t &number, int_t &largest, int_t &smallest) {
cout << " >";
while (!(cin >> number)) {
cout << "Try again." << endl;
cout << "> ";
cin.clear(); cin.ignore(10000, '\n');
}
smallest = min(smallest, number);
largest = max(largest, number);
return number;
}
int main()
{
cout << " Enter numbers to find the smallest and largest integer. " << endl;
cout << " Enter -99 to quit " << endl;
int_t largest = numeric_limits<int_t>().min();
int_t smallest = numeric_limits<int_t>().max();
int_t number = get_number(number, largest, smallest);
while(-99 != number) {
number = get_number(number, largest, smallest);
}
cout << " The smallest number you entered was " << smallest << endl;
cout << " The largest number you entered was " << largest << endl;
return 0;
}
you're facing the problem because when the user inputs -99, you're storing that in smallest as well. Try the code below which only overwrites the number if it is smaller AND if it is not -99
// Evaluate user input
if (number < smallest && number != -99)
{
smallest = number;
}

For loop - Magic number program

What changes should I make so that the user of this code can guess at the amount of magic numbers they choose, with three different chances to guess at each magic number? I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
int magic; // This is a random number between 1 and 20
int guess; // This is the guess number being attempted (up to 3 guesses)
int magicguesses; // This is the amount of magic numbers being guessed attempted
int i;
int number; // This is the number the user guessed
bool numberismagic = false; // This is the flag variable
unsigned int seed;
seed = time(NULL);
srand(seed);
magic = rand() % 20 + 1;
cout << "How many magic numbers would you like to guess at today?\n";
cin >> magicguesses;
for (i = 1; i < magicguesses + 1; i++)
{
cout << "This is trial number:" << i << endl;
for (guess = 1; (guess < 4) && (!numberismagic); guess++)
{
cout << "This is guess number:" << guess << endl;
cout << "Guess a number between 1 and 20:" << endl;
cin >> number;
while ((number < 1) || (number > 20))
{
cout << "Your guess is invalid; guess a number between 1 and 20 \n";
cin >> number;
cout << endl;
}
if (number == magic)
{
cout << "You have guessed the magic number correctly! \n";
numberismagic = true;
}
else
{
cout << "Sorry - you guessed incorrectly! \n";
if (number > magic)
cout << "Your guess is too high \n" << endl;
else
cout << "Your guess is too low \n" << endl;
}
}
if (number != magic)
cout << "The magic number is:" << magic << endl;
}
return 0;
}
I'm not sure what your first question is, but for this question "I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly", you should edit the variable magic inside the first for loop so the magic number changes after the user guesses correctly or they run out of tries.
for (i=1;i<magicguesses+1;i++)
{
//magic equals new random number
//the rest of your code
}

Bar graph program behaving strangely

I have to make a program for a class that displays one star for every three degrees for each temperature read from an input file. I think I did ok, the code compiles. However, when I actually run it, I have a few problems:
1) when I run it without pressing ctrl+f5 in codelite it exits immediately, even though I have 'return 0;' at the end.
2) the console only shows stars for maybe half of the numbers, the rest are blank.
3) the numbers aren't lining up although I have set them all to the same width in my loop.
Here's what I see when I use ctrl+f5: http://imgur.com/w6jqPp5
Here's my code:
#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
//declare variables for input/loops
string graphLine = " | ";
int tempCount = 0;
int tempStars;
int tempValue;
int printedStars;
//Title
cout << "Welcome to the Hourly Temperature Bar-Graph Maker 1.0!" << endl;
//read input file, name it "tempData"
ifstream tempData;
tempData.open("temperatures.txt");
//display error if the input file read failed
if(!tempData) {
cout << "ERROR: The input file could not be read." << endl;
return 0;
}
cout << "Temperatures for 24 hours(each asterisk represents 3 degrees): " << endl;
//print the temperature range(horizontal label for graph)
cout << "-30 0 30 60 90 120" << endl;
//read a temperature, output the bar for each temperature
while (tempCount < 24) {
//read in temperature value
tempData >> tempValue;
//distinguish between negative and positive temperatures
if(tempValue >= 0) {
tempStars = tempValue/3;
cout << tempValue << setw(5) << graphLine;
//print the appropriate number of asterisks for the temperature
while (printedStars < tempStars) {
cout << '*';
printedStars++;
}
cout << endl;
}
//print the stars before the line
else {
tempStars = tempValue/3;
while (printedStars < tempStars) {
cout << '*';
printedStars++;
}
cout << tempValue << setw(5) << graphLine << endl;
}
tempCount++;
}
tempData.close();
return 0;
}
The program is just finishing normally - put a call to cin.getline or some other input call if you want it to wait. Alternatively run it through the debugger and put a breakpoint on the return 0 line.
You don't initialize or reset printedStars before you use it. Put printedStars = 0; before your star printing loops.
Move the setw(5) bit in the cout calls to before the value, so the value is output with a width of 5.