C++ Creating Lottery Guessing Program - c++

Okay so the project is to create a lottery number composed of 10 random positive integers and the user is suppose to guess it until the user guesses the correct number. All of my code looks good but when I run the program and enter in a number it gives me this MSVS Runtime Library error? I dont even know what it means as I am fairly new to programming. Help would be very appreciated!
Main.cpp
#include <iostream>
#include <cmath>
#include <ctime>
#include "Lottery.h"
using namespace std;
int main() {
const int size = 9; //declare variables
int win[size];
int g;
srand(time(NULL));
assign(win, size);
draw(win, size);
g = entry();
if (check(win,size,g) == true) {
cout << "Congradulations! You have won the lottery!" << endl;
}
else {
cout << "Try again!" << endl;
}
printOut(g);
}
Lottery.cpp
#include <iostream>
#include <cmath>
#include "Lottery.h"
using namespace std;
int entry() {
int guess;
cout << "Enter a number from 0 to 99." << endl;
cin >> guess;
return guess;
}
void assign(int w[], int s) {
for (int i = 0; i < s; i++) {
w[s] = -1;
}
}
bool check(int w[], int s, int g) {
for (int i = 0; i < s; i++) {
if (g == w[i]) {
return true;
}
}
return false;
}
void draw(int w[], int s) {
for (int i = 0; i < s; i++) {
int tmp = rand() % 100;
if (check(w, s, tmp)) {
i--;
}
else
w[i] = tmp;
}
}
void printOut(int g) {
cout << "Numbers you have chosen:" << " " << g << endl;
}
Lottery.h
#ifndef LOTTERY_INCLUDED
#define LOTTERY_INCLUDED
void assign(int[], int);
bool check(int[], int, int);
void draw(int[], int);
int entry();
void printOut(int);
#endif //LOTTERY

Debugging tutorials are available elsewhere. But if something bad happens, don't panic and look for instructions.
First, your runtime error:
This has a link "Break and open exception settings" link or a "Break" button. Break which will take you to the end of main if you click it.
The details say we did something bad near win.
Look at this:
void assign(int w[], int s) {
for (int i = 0; i < s; i++) {
w[s] = -1; //<------Oh oops!
}
}
We know the length of the array is s i.e. 9, and are using w[s] where we clearly meant w[i].
The extra details in the error are telling you a possible place to look.

Related

Struct doesn't print with cout

I'm trying to print the structure in an array whose int prejetih member is highest.
#include <iostream>
using namespace std;
struct Tekma {
int prejetih;
};
Tekma najvec_kosev(Tekma tekme[]) {
int maksi = 0, index = 0;
for (int i = 0;i < 2;i++) {
if (maksi < tekme[i].prejetih) {
index = i;
maksi = tekme[i].prejetih;
}
}
return tekme[index];
}
void vpis(Tekma tekme[]) {
for (int i = 0;i < 2;i++)
cin >> tekme[i].prejetih;
}
int main() {
Tekma tekme[2];
vpis(tekme);
cout << najvec_kosev(tekme);
}
The compiler reports
C++ no operator matches these operands
operand types are: std::ostream << Tekma
over cout << najvec_kosev(tekme);
Here using a solution with std::vector and fixing your cout problem:
#include <iostream>
#include <vector>
using namespace std;
struct Tekma {
int prejetih;
};
Tekma najvec_kosev(vector<Tekma>& tekme) {
Tekma lowest = tekme[0]
for(auto& t : tekme) {
if(lowest.prejetih < t.prejetih) {
lowest = t;
}
}
return lowest ;
}
void vpis(vector<Tekma>& tekme) {
int input;
while(true) {
cin >> input;
// Check if the input is valid else quit the loop.
if(input == valid) {
Tekma newStruct = {input};
tekme.push(newStruct);
}
else {
// Stop the loop
break;
}
}
}
int main() {
vector<Tekma> tekme;
vpis(tekme);
cout << najvec_kosev(tekme).prejetih; // This fixes your error.
}

Passing array values using pointer

I have two functions one is for file reading and another one for little sorting of numbers. With function read() I am reading file's each line and put each line into array. File looks like:
1
2
3
With function sort() I want to print only numbers with value greater than 1.
What is wrong: I got printed two arrays, but my sort array still printing all values, not only greater than 1.
My code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
class UZD
{
private:
int numLines;
int *value;
public:
UZD();
int * read();
int sort();
};
// =========================================================
UZD::UZD()
{
}
// =========================================================
int * UZD::read(){
ifstream myfile("stu.txt");
int value[20];
string line[20];
int i=0;
while(!myfile.eof() && i < 20) {
getline(myfile,line[i]);
++i;
}
numLines = i;
for (i=0; i < numLines; ++i) {
value[i] = atoi(line[i].c_str());
cout << i << ". " << value[i]<<'\n';
}
return value;
}
// =========================================================
int UZD::sort(){
int *p;
p = read();
int i;
if(p[i] > 1) {
cout << p <<'\n';
}
}
// =========================================================
int main() {
UZD wow;
wow.read();
wow.sort();
}
There are many issues in your code, the most obvious one is "return value" in the read() method. Value is a local array and will be gone once out of scope of read(). Also the design seems faulty. You are calling read() twice, once from the main() and again internally from sort().
I have written a working code, using vectors. Probably this is what you are expecting:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>
using namespace std;
class UZD
{
private:
int numLines;
vector<int> value;
public:
UZD();
vector<int> & read();
void sort();
};
// =========================================================
UZD::UZD()
{
}
// =========================================================
vector<int> & UZD::read(){
ifstream myfile("stu.txt");
vector<string> line(20);
int i=0;
while(!myfile.eof() && i < 20) {
getline(myfile,line[i]);
++i;
}
numLines = i;
cout << "After reading file: " << endl;
for (i=0; i < numLines; ++i) {
value.push_back(atoi(line[i].c_str()));
cout << i << ". " << value[i]<<'\n';
}
return value;
}
// =========================================================
void UZD::sort(){
cout << "Inside sort()" << endl;
for(int i=0; i<value.size(); ++i){
if(value[i] > 1)
cout << value[i] << endl;
}
}
// =========================================================
int main() {
UZD wow;
wow.read();
wow.sort();
return 0;
}
I have kept the variable names same for clarity. Let me know if you don't get anything.
There are a lot of issues in your program; just to mention some of them:
In sort, you use variable i uninitialized, which is undefined behaviour (probably crashes); You write while(!myfile.eof()..., which is usually considered wrong (see this SO answer; The use of atoi is not recommended, as it is not safe if the parameter does not represent a number; You return a pointer to a local variable, which is destroyed one going out of scope; You declare member variables, but pass through local ones (e.g. value)...
See the following code which demonstrates the usage of int* and a vector<int>; hope it helps.
class UZD
{
private:
int numLines;
int *value = nullptr;
public:
~UZD() {
if (value)
delete value;
};
void read();
void print();
};
// =========================================================
void UZD::read(){
ifstream myfile("stu.txt");
value = new int[20];
int val;
numLines = 0;
while(numLines < 20 && myfile >> val) {
value[numLines] = val;
numLines++;
}
}
// =========================================================
void UZD::print(){
for (int i=0; i<numLines; i++)
cout << value[i] << endl;
}
class UZD_vector
{
private:
vector<int> values;
public:
void read();
void print();
};
// =========================================================
void UZD_vector::read(){
ifstream myfile("stu.txt");
int val;
while(myfile >> val) {
values.push_back(val);
}
}
// =========================================================
void UZD_vector::print(){
for (auto val : values)
cout << val << endl;
}
// =========================================================
int main() {
cout << "with int[]:" << endl;
UZD wow;
wow.read();
wow.print();
cout << "with vector:" << endl;
UZD wow_vector;
wow_vector.read();
wow_vector.print();
}
Here is your own code rectified, just in case you find vectors too difficult to learn (which should not be true, though)
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
class UZD
{
private:
int numLines;
int *value;
int num;
public:
UZD();
void read();
void sort();
};
// =========================================================
UZD::UZD():num(20)
{}
// =========================================================
void UZD::read(){
ifstream myfile("stu.txt");
value = new int[num];
string line[num];
int i=0;
while(!myfile.eof() && i < num) {
getline(myfile,line[i]);
++i;
}
numLines = i;
for (i=0; i < numLines; ++i) {
value[i] = atoi(line[i].c_str());
cout << i << ". " << value[i]<<'\n';
}
}
// =========================================================
void UZD::sort(){
cout << "After sorting: " << endl;
for (int i = 0; i < num; ++i) {
if(value[i] > 1)
cout << value[i] << endl;
}
}
// =========================================================
int main() {
UZD wow;
wow.read();
wow.sort();
return 0;
}

Reference array from class in an other class

I'm writing a program that converts decimal numbers into binary, octal and hexadecimal. I'm doing each conversion in different class, but i want to use the binary form of the number which is stored in an array(bin[31]) inside the 1st class. Is there a way to use that array in my other classes? My teacher said i should use references, but i don't know how to do it. My files are:
Binary.h
#ifndef BINARY_H
#define BINARY_H
class Binary{
public:
int num_;
static int bin[31];
int i;
int x;
Binary();
void Set(int temp);
int Get();
void ChangeToBinary();
void ChangeToBinaryComplement();
void TwoComplement();
void PrintBinary();
~Binary();
};
# endif
Binary.cpp
#include <stdio.h>
#include <iostream>
#include "Binary.h"
#include "Octal.h"
using namespace std;
Binary::Binary(){
}
void Binary::Set(int temp){
num_ = temp;
}
int Binary::Get(){
return num_;
}
void Binary::ChangeToBinary(){
x = 1;
for (i=0;i<30;i++){
x*=2;
}
for (i = 0; i<31;i++){
if (num_ -x >= 0){
bin[i] = 1;
num_ = num_ -x;
}
else{
kettes[i] = 0;
} x=x/2;
}
}
void Binary::ChangeToBinaryComplement(){
for (i=0;i<31;i++){
if (bin[i] ==0){
bin[i] = 1;
}
else {
bin[i] = 0;
}
}
}
void Binary::TwoComplement(){
for(i=30;i>0;i--){
if(bin[i] == 0){
bin[i] = 1;
break;
} else{
bin[i] = 0;
}
}
}
void Binary::PrintBinary(){
for (i=0;i<31;i++){
cout << bin[i];
}
cout << " " << endl;
}
Binary::~Binary()
{
}
Octal.h
#ifndef OCTAL_H
#define OCTAL_H
class Octal{
private:
int* oct_ = new int[10];
int i;
public:
Octal();
void ConvertToOctal();
void PrintOctal();
~Octal();
};
#endif
Octal.cpp
#include <stdio.h>
#include <iostream>
#include "Binary.h"
#include "Octal.h"
using namespace std;
Octal::Octal()
{
}
void Octal::ConvertToOctal(){
int k = 0;
int z = 0;
int o = 0;
for(i=0;i<31;i++){
if((help[i] ==1) && (k==0)){
z = z + 4;
k = k + 1;
}
else if((help[i] ==1) && (k==1)){
z = z + 2;
k = k + 1;
}
else if((help[i] ==1) && (k==2)){
z = z + 1;
k = k + 1;
}
else{
k = k + 1;
}
if(k==3){
oct_[o]=z;
z=0;
k=0;
o = o + 1;
}
}
}
void Octal::PrintOctal(){
for(i=0;i<10;i++){
cout << oct_[i];
}
}
Octal::~Octal()
{
}
If you have to use your own classes
You can add a method inside the Binary class that lets you get access to the pointer to the array containing the data. The method would probably look like this:
int getData(){
return bin;
}
You can also access the array directly using Binary::bin, which will also give you a pointer to the first element of the array.
It would be much better tho if you changed the array type from int to bool or char. If you want to do it even better - use the vector< bool > template class. It's basically an array of bools. You can read about it in the C++ Reference
If you just need the funcionality
You should really just use the standard manipulators. There is no real reason to reinvent the wheel. The easiest way to do this is by inputting a number into a stream, and outputing it into a string. Like this:
#include<string> // string
#include<sstream> // stringstream
#include<iostream> // cin, cout
#include<iomanip> // setbase
using namespace std;
int main(){
int number;
cin >> number;
stringstream parser;
parser << setbase(16) << number;
string convertedNumber;
parser >> convertedNumber;
cout << endl << convertedNumber << endl;
return 0;
}
Of course you can change the base inside the setbase manipulator.

How to alphabetically sort strings?

I have been trying to use this c++ program to sort 5 names alphabetically:
#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;
int main()
{
char names[5][100];
int x,y,z;
char exchange[100];
cout << "Enter five names...\n";
for(x=1;x<=5;x++)
{
cout << x << ". ";
cin >> names[x-1];
}
getch();
for(x=0;x<=5-2;x++)
{
for(y=0;y<=5-2;y++)
{
for(z=0;z<=99;z++)
{
if(int(names[y][z])>int(names[y+1][z]))
{
strcpy(exchange,names[y]);
strcpy(names[y],names[y+1]);
strcpy(names[y+1],exchange);
break;
}
}
}
}
for(x=0;x<=5-1;x++)
cout << names[x];
return 0;
}
If I enter Earl, Don, Chris, Bill, and Andy respectively, I get this:
AndyEarlDonChrisBill
Could someone please tell me whats wrong with my program?
You could use std::set or std::multiset (if you will allow repeated items) of strings, and it will keep the items sorted automatically (you could even change the sorting criteria if you want).
#include <iostream>
#include <set>
#include <algorithm>
void print(const std::string& item)
{
std::cout << item << std::endl;
}
int main()
{
std::set<std::string> sortedItems;
for(int i = 1; i <= 5; ++i)
{
std::string name;
std::cout << i << ". ";
std::cin >> name;
sortedItems.insert(name);
}
std::for_each(sortedItems.begin(), sortedItems.end(), &print);
return 0;
}
input:
Gerardo
Carlos
Kamilo
Angel
Bosco
output:
Angel
Bosco
Carlos
Gerardo
Kamilo
You can use the sort function:
#include <algorithm>
#include <vector>
using namespace std;
...
vector<string> s;
sort(s.begin(),s.end());
You are using too much unnecessary loops. Try this simple and efficient one. You need to just swap when a string is alphabetically latter than other string.
Input
5
Ashadullah
Shawon
Shakib
Aaaakash
Ideone
Output
Aaaakash
Ashadullah
Ideone
Shakib
Shawon
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s[200],x[200],ct,dt;
int i,j,n;
cin>>n;
for(i=0;i<n;i++)
{
cin>>s[i];
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i]>s[j])
{
ct=s[i];
s[i]=s[j];
s[j]=ct;
}
}
}
cout<<"Sorted Name in Dictionary Order"<<endl;
for(i=0;i<n;i++)
{
cout<<s[i]<<endl;
}
return 0;
}
Your code implements a single-pass of bubble sort. Essentially missing the 'repeat until no changes are made to the array' loop around the outside.
The code does not take care when the names are already in order. Add the following
else if(int(names[y][z])<int(names[y+1][z]))
break;
To the if statement.
Putting this here in case someone needs a different solution.
/* sorting example */
#include <iostream>
using namespace std;
bool isSwap( string str1, string str2, int i)
{
if(str1[i] > str2[i])
return true;
if(str1[i] == str2[i])
return isSwap(str1,str2,i+1);
return false;
}
int main()
{
string str[7] = {"you","your","must","mike", "jack", "jesus","god"};
int strlen = 7;
string temp;
int i = 0;
int j = 0;
bool changed = false;
while(i < strlen-1)
{
changed = false;
j = i+1;
while(j < strlen)
{
if(isSwap(str[i],str[j],0))
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
changed = true;
}
j++;
}
if(changed)
i = 0;
else
i++;
}
for(i = 0; i < strlen; i++)
cout << str[i] << endl;
return 0;
}

C++ stacks and 2D array

I have been working on a Project that is suppose to simulate link list by using 2D array for stacks. I have the code but I can not figure out how to make the Random numbers work. I have looked online but online doesn't explain how to make the random function work with the simulation. Here is my code below:
`#include <iostream>
#include <stdlib.h>
using namespace std;
int myTop = -1;
int index = -1;
int next = -1;
int tt[25][2];
void construct()
{
tt[25][2];
}
void empty()
{
if (myTop == -1)
cout << "Empty Stack";
else
cout << "Full Stack";
}
void push(int x)
{
if (myTop < 24)
{
myTop++;
tt[myTop] = x;
}
else
cout << "The stack is full.";
}
void top()
{
if (myTop != -1)
cout << "Top Value is: " << tt[myTop];
else
cout << "Empty Stack";
}
int pop()
{
int x;
if(myTop<=0)
{
cout<<"stack is empty"<<endl;
return 0;
}
else
{
x=tt[myTop];
myTop--;
}
return(x);
}
void display()
{
for (int row=0; row<25; row++)
{
for (int column=0; column<3; column++)
{
cout << tt[row][column] << "\t";
if (column == 2)
cout << endl;
}
}
cout << endl;
}
int main()
{
push(rand() % 25);
display();
push(rand() % 25);
display();
push(rand() % 25);
display();
push(rand() % 25);
display();
top();
pop();
display();
top();
pop();
display();
top();
pop();
display();
}
You haven`t initialized the random number generator (this is called "seeding").
Add the following to your code.
#include <time.h>
srand (time(0));
And on another note, I prefer using ctime and cstdlib as those are c++ headers (although this can be debated). Also, look into the random header if you have access to an up-to-date compiler.
Rand():
http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Srand():
http://www.cplusplus.com/reference/clibrary/cstdlib/srand/
Here is how to use random numbers in C++
#include <cstdlib>
#include <ctime>
int main ()
{
srand(time(NULL));
number = rand() % 10 + 1; # Random number between 1 and 10
}