This might be a stupid question I'm still very new to coding. For my CS class I was given code for the basics of a boardgame. When I try to run the code it just comes up blank in my console, I tried to print "check" at the very beginning of main but still nothing prints to the console. No errors come up
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
class square {
private:
int move;
string message;
char symbol;
public:
square();
void print();
int action();
void set(int, char, string);
};
void print_board(square[], int, int);
void read_board(square[]);
void check_position(int &);
const int board_length = 20;
int main() {
cout << "check";
int current_player = 1, roll;
int player1_position = 0, player2_position = 0;
square the_board[board_length];
srand(time(NULL));
read_board(the_board);
print_board(the_board, player1_position, 1);
print_board(the_board, player2_position, 2);
do {
cout << "\n\n\nPlayer " << current_player << " type enter to roll.\n";
cin.ignore();
roll = 1 + (rand() % 5);
cout << "Player " << current_player << " rolled a " << roll << ".\n";
if (current_player == 1) {
player1_position += roll;
check_position(player1_position);
player1_position += the_board[player1_position].action();
check_position(player1_position);
} else {
player2_position += roll;
check_position(player2_position);
player2_position += the_board[player2_position].action();
check_position(player2_position);
}
print_board(the_board, player1_position, 1);
print_board(the_board, player2_position, 2);
current_player = (current_player % 2) + 1;
} while ((player1_position < board_length-1) && (player2_position < board_length - 1));
current_player = (current_player % 2) + 1;
cout << "\nPlayer " << current_player << " Wins!!!\n";
cin.ignore();
return 0;
}
void read_board(square b[]) {
ifstream infile;
infile.open("game.txt");
int square_number, square_move;
string square_message;
char square_symbol;
while (!infile.eof()) {
infile >> square_number >> square_move >> square_symbol;
getline(infile, square_message);
if (square_number < board_length) {
b[square_number].set(square_move, square_symbol, square_message);
}
}
}
void print_board(square b[], int player_position, int player_number) {
for (int i=0; i < board_length; i++) {
if (i != player_position) {
b[i].print();
} else {
cout << player_number;
}
}
cout << "Goal\n";
for (int i=0; i < board_length; i++) {
cout << "-";
}
cout << "\n";
}
void check_position(int &p) {
if (p < 0) {
p = 0;
}
if (p >= board_length) {
p = board_length - 1;
}
}
square::square() {
symbol = ' ';
move = 0;
message = "";
}
int square::action() {
cout << message << endl;
return move;
}
void square::print() {
cout << symbol;
}
void square::set (int m, char s, string a_message) {
move = m;
symbol = s;
message = a_message;
}
Modify you read_board() to
void read_board(square b[]) {
ifstream infile;
infile.open("game.txt");
int square_number, square_move;
string square_message;
char square_symbol;
while (infile >> square_number >> square_move >> square_symbol) {
getline(infile, square_message);
if (square_number < board_length) {
b[square_number].set(square_move, square_symbol, quare_message);
}
}
}
Change cout<<"check"; to cout<<"check"<<endl;
Without the new line added, the out buffer is not flushed before your code gets hung in your read_board function
Related
I want to write a program that adds words to a lexicon with pointers. However, I must not use strdup(), how can I do that? Below is what I tried but it gives me this error:
Exception thrown at 0x7C87EE72 (ucrtbased.dll) in (name of the file.exe): 0xC0000005: Access violation writing location 0xCDCDCDCD.
The problem is in the newStr() function.
#include <cstring>
#include <string>
#pragma warning (disable:4996)
#include <iostream>
using namespace std;
void delStr(char**&, int&, char*);
void newStr(char**&, int&, char*);
void printchar(char**, int, char);
char* searchStr(char**&, int&, char*);
void printAll(char**&, int);
enum ACTIONS { NEW, DELETE, SEARCH, PRINTLETTER, PRINTALL, EXIT };
int main() {
char** lexicon = NULL;//pointer to pointer fo the dictionary
int x = 0;
int size = 0;
char word[81];
char ch;
cout << "Enter 0-5:" << endl;
cin >> x;
while (x < 0 || x > 5) {//while loop for correct input
cout << "ERROR" << endl;
cin >> x;
}
while (x >= 0 && x <= 5) {
switch (x) {
case NEW:
cout << "Enter the word:" << endl;
ch = cin.get();
cin.getline(word, 80);
newStr(lexicon, size, word);
printAll(lexicon, size);
break;
case DELETE:
cout << "Enter the word to delete:" << endl;
ch = cin.get();
cin.getline(word, 80);
delStr(lexicon, size, word);
printAll(lexicon, size);
cout << endl;
break;
case SEARCH:
cout << "Enter the word to search for:" << endl;
ch = cin.get();
cin.getline(word, 80);
searchStr(lexicon, size, word);
break;
case PRINTLETTER:
cout << "Enter the char:" << endl;
ch = cin.get();
ch = cin.get();
printchar(lexicon, size, ch);
cout << endl;
break;
case PRINTALL:
if (size > 0 && lexicon != NULL) {
printAll(lexicon, size);
}
break;
case EXIT:
return 0;
break;
}
cout << "Enter your choice:" << endl;
cin >> x;
while (x < 0 || x > 5) {//while loop for correct input
cout << "ERROR" << endl;
cin >> x;
}
}
return 0;
}
void printAll(char**& lex, int size) {
for (int i = 0; i < size; i++) {
cout << lex[i] << " ";
}
cout << endl;
}
void newStr(char**& lex, int& size, char* word) {
int i = 0;
for (i = 0; i < size; i++) {
if (strcmp(lex[i], word) == 0) {
//cout << "Word " << word << " already exists\n";
return;
}
}
if (size == 0) {
lex = new char* [1];
for (int i = 0; i < strlen(word); i++) {
strcpy(*lex, word);
}
size++;
}
else {
char** temp = new char* [size + 1];
for (i = 0; i < size; i++) {
temp[i] = lex[i];
}
//strcpy(temp[size],word);
strcpy(temp[size], word);
delete[] lex;
lex = temp;
size++;
}
}
void delStr(char**& lex, int& size, char* word) {
int j = 0;
for (int i = 0; i < size; i++) {
if (strcmp(lex[i], word) == 0) {
for (j = i; j < size - 1; j++) {
lex[j] = lex[j + 1];
}
size--;
char** temp = new char* [size];
for (j = 0; j < size; j++) {
temp[j] = lex[j];
}
delete[] lex;
lex = temp;
}
}
}
void printchar(char** lex, int size, char ch) {
for (int i = 0; i < size; i++) {
if (lex[i][0] == ch) {
cout << lex[i] << " ";
}
}
}
char* searchStr(char**& lex, int& size, char* word) {
for (int i = 0; i < size; i++) {
if (strcmp(lex[i], word) == 0) {
cout << "Found" << endl;
//cout << "Word " << word << " already exists\n";
return lex[i];
}
}
cout << "Not found";
return NULL;
}
I have a class ComplexesSet which represent a set of complexes numbers. I have to use this class to write a program which reads the complex numbers from keyboard and create a menu like that: press 1 to add a number in the set, press 2 to delete a number from set and press 0 to exit the program.
This is my program:
HEADER FILE
#pragma once
#include <iostream>
using namespace std;
#define DIMMAX 10;
class Complex {
int re, im;
public:
Complex() {
re = im = 0;
}
Complex(int re, int im) {
this->re = re;
this->im = im;
}
void display() {
cout << " (" << re << ", " << im << " ) ";
}
int equal(Complex c2); // check the equality between 2 complex numbers.
void read(); // reads a complex number
};
class ComplexesSet {
Complex* v; // the complex numbera array
int dim; // the maximum dimension of the array
int n; // the current number of complex numbers in the set
public:
ComplexesSet();
ComplexesSet(int d);
~ComplexesSet();
void addNumber(Complex); // add a number in set
void deleteNumber(Complex); // delete a number from set
void displaySet(); // display the set
};
METHODS FILE
#include "multime.h"
#include <iostream>
using namespace std;
int Complex::equal(Complex c2) {
if (this->re == c2.re && this->im == c2.im) {
return 1;
}
else {
return 0;
}
}
void Complex::read() {
cout << "Enter the real part: ";
cin >> this->re;
cout << "Enter the imaginary part: ";
cin >> this->im;
cout << endl;
}
ComplexesSet::ComplexesSet() {
cout << "Set of complexes numbers: ";
dim = DIMMAX;
v = new Complex[dim];
n = 0;
}
ComplexesSet::ComplexesSet(int d) {
cout << "ComplexesSet(" << d << ")";
dim = d;
v = new Complex[dim];
n = 0;
}
ComplexesSet::~ComplexesSet() {
cout << "~ComplexesSet" << endl;
if (v) {
delete[] v;
}
v = nullptr;
dim = -1;
n = -1;
}
void ComplexesSet::addNumber(Complex num) {
int ok = 0;
if (n < dim) {
for (int i = 0; i < n; i++) {
if (v[i].equal(num)) {
ok = 1;
i = n + 1;
}
}
if (ok) {
cout << "This element is already in the set.";
}
else {
v[n] = num;
n++;
}
}
else {
cout << "The set is full.";
}
}
void ComplexesSet::deleteNumber(Complex num) {
int i;
if (n != 0) {
for (i = 0; i < n; i++) {
if (v[i].equal(num)) {
break;
}
else {
cout << "This element does not exists.";
}
}
if (i < n) {
n = n - 1;
for (int j = i; j < n; j++) {
v[j] = v[j + 1];
}
}
}
else {
cout << "The set is empty.";
}
}
void ComplexesSet::displaySet() {
cout << "\n The set: {";
if (n) {
for (int i = 0; i < n; i++) {
v[i].display();
}
}
cout << "}.\n\n";
}
MAIN FILE:
#include "multime.h"
#include <iostream>
using namespace std;
int main() {
ComplexesSet m;
Complex num;
int option;
int x;
do {
cout << endl << "1 - ADD A NUMBER\n 2 - DELETE A NUMBER\n 0 - EXIT THE PROGRAM";
cin >> option;
switch (option) {
case 1:
cout << endl << "Enter the number you want to add: ";
num.read();
//? How to call addNumber method from ComplexesSet class?
// m.displaySet ?;
break;
case 2:
cout << endl << "Enter the number you want to delete: ";
num.read();
//? How to call deleteNumber method from ComplexesSet class?
// m.displaySet ?;
break;
}
} while (option >= 1 && option <= 2);
system("pause");
return 0;
}
I got stuck in the main file. How to call the addNumber and deleteNumber methods in order to add and delete a complex number from the set? Also, after pressing "1" or "2", after I read the number, I need to display the set.
I guess that my problem is very trivial, but unfortunately (maybe because I'm really tired) I can't find a solution by myself. Well, my program generates results that I would like to write to successive lines of a text file, because I need to create a graph from them. Unfortunately, in my case, each result is saved in the same line by removing the previous result. Can you help me to improve this code? Thank you.
#include <iostream>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <fstream>
using namespace std;
int fp(int x, int y)
{
return (x<=y);
}
void sort_shell(int *tablica, int ilosc)
{
int licznik=0;
int h;
int i;
int temp;
int c=1;
fstream plik;
for (h=1; h<=ilosc/9; h=ilosc/pow(2,h));
c++;
for(; h>0; h /= 3)
{
for (i=h; i<ilosc; i++)
{
int j;
temp = tablica[i];
for (j = i-h ; j>=0; j -=h)
{
if (temp <=tablica[j])
{
tablica[j+h] = tablica[j];
licznik++;
}
else
break;
}
tablica[j+h] = temp;
}
}
/*cout << "\nPo sortowaniu Shellem." << endl;
for(i=0; i<ilosc; i++)
{
cout << tablica[i] << "\t";
}*/
plik.open( "shell.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
void sort_hibbard(int x[], int n)
{
int i, j,k, increment, temp,licznik=0;
long swp=0, comp=0;
int val;
fstream plik;
val=log(n+1)/log(2);
increment =pow(2,val)-1;
while (increment > 0)
{
for (i=0; i<increment; i++)
{
for(j=0; j<n; j+=increment)
{
temp=x[j];
for(k=j-increment; k>=0&&temp<x[k]; k-=increment)
{
comp++;
swp++;
x[k+increment]=x[k];
licznik++;
}
x[k+increment]=temp;
swp++;
licznik++;
}
}
comp++;
val--;
if(increment!=1)
increment=pow(2,val)-1;
else
increment = 0;
}
/*cout << "\nPo sortowaniu Hibbardem." << endl;
for(i=0; i<n; i++)
{
cout << x[i] << "\t";
}*/
plik.open( "hibbard.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
void sort_sedgewick(int *tablica, int ilosc)
{
int h = 0, i, g, t, j;
int c = 1;
int licznik = 0;
int temp;
fstream plik;
vector <int> tmp;
tmp.push_back(h);
do
{
h = (pow(4,c) + (3 * pow(2,c-1)) + 1); // funkcja z wikipedi O(N^4/3)
tmp.push_back(h);
if(h < ilosc) c++;
}while(h < ilosc);
for(g=ilosc/c;g>0;g/=c)
{
for(i=ilosc-g-1;i>=0;i--)
{
t = tablica[i];
for(j=i+g;(j<ilosc)&&!fp(t,tablica[j]);j+=g)
{
tablica[j-g] = tablica[j];
licznik++;
}
tablica[j-g] = t;
licznik++;
}
}
/*cout << "\nPo sortowaniu SEDGEWICKiem." << endl;
for(i=0;i<ilosc;i++)
{
cout << tablica[i] << "\t";
}*/
plik.open( "sedgewick.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
int main()
{
int i, n;
//cout << "Podaj rozmiar tablicy (W tablicy znajda sie liczby od 1 do 100): ";
//cin >> n;
for(n=1000;n<=100000;n+=1000)
{
cout << n << "\n";
int zbior[n];
int prawy = 200;
srand(time(NULL));
//cout << "Przed sortowaniem." << endl;
for (int i = 0; i < n; i++)
{
if (i%2 == 0)
{
zbior[i] = rand()%prawy;
//cout << zbior[i] << "\t";
}
else
{
zbior[i] = rand()%prawy+200;
//cout << zbior[i] << "\t";
}
}
cout << endl;
sort_shell(zbior, n);
sort_hibbard(zbior, n);
sort_sedgewick(zbior, n);
}
return 0;
}
You need to use std::ios::app to append data to a file. You should also keep these files open for the duration of the reporting; you seem to be re-opening them for each iteration.
I'm having an issue sorting an array of 1000 integers with the following code. It worked fine with 10 integers but with 1000 it seems keep going I'm assuming it's some kind of memory leak.
I've never sorted before a small explanation of my errors would be helpful also.
Thank you
class RandomNumbers
{
private:
int intRandomNumbers;
public:
int getRandomNumbers();
void setRandomNumbers(int intPRandomNumbers);
RandomNumbers(void);
};
-----------------------------------------------------------
void printArray(const int intArray[], int intLength);
int searchFull(const int intArray[], int intLength, int intSearchItem);
void sortBubble(int intArray[], int intLength);
int searchLinear(const int intArray[], int intLength, int intSearchItem);
int searchBinary(const int intArray[], int intLength, int intSearchItem);
--------
//Getters and setters for RandomNumber class.
RandomNumbers::RandomNumbers()
{
setRandomNumbers(0);
}
void RandomNumbers::setRandomNumbers(int intPRandomNumbers)
{
intRandomNumbers = intPRandomNumbers;
}
int RandomNumbers::getRandomNumbers()
{
return intRandomNumbers;
}
void printArray(const int intArray[], int intLength) {
for(int intIndex = 0; intIndex < intLength - 1; intIndex++) {
cout << intArray[intIndex] << ", ";
}
cout << intArray[intLength - 1] << endl;
}
int searchFull(const int intArray[], int intLength, int intSearchItem) {
int intLocation = -1;
int intCounter = 1;
for(int intIndex = 0; intIndex < intLength; intIndex++) {
cerr << "searchFull: " << intCounter++ << endl;
if(intArray[intIndex] == intSearchItem)
{
intLocation = intIndex;
}
}
return intLocation;
}
void sortBubble(int intArray[], int intLength){
int intTemp = 0;
int intIteration = 0;
int intIndex = 0;
for(intIteration = 1; intIteration < intLength; intIteration++) {
for(intIndex = 0; intIndex < intLength - intIteration; intIndex++) {
if(intArray[intIndex] > intArray[intIndex + 1]) {
intTemp = intArray[intIndex];
intArray[intIndex] = intArray[intIndex + 1];
intArray[intIndex + 1] = intTemp;
}
printArray(intArray,intLength);
}
}
}
int searchLinear(const int intArray[], int intLength, int intSearchItem) {
int intLocation = -1;
int intCounter = 1;
for(int intIndex = 0; intIndex < intLength && intSearchItem >= intArray[intIndex]; intIndex++) intIndex++)
{
cerr << "searchLinear: " << intCounter++ << endl;
if(intArray[intIndex] == intSearchItem)
{
intLocation = intIndex;
}
}
return intLocation;
}
int searchBinary(const int intArray[], int intLength, int intSearchItem) {
int intFirstIndex = 0;
int intLastIndex = intLength - 1;
int intMiddle = 0;
bool boolFound = false;
while(intFirstIndex <= intLastIndex && !boolFound) {
intMiddle = (intFirstIndex + intLastIndex) / 2;
if(intArray[intMiddle] == intSearchItem) {
boolFound = true;
} else if(intArray[intMiddle] > intSearchItem) {
intLastIndex = intMiddle - 1;
} else {
intFirstIndex = intMiddle + 1;
}
cerr << "searchBinary: " << intFirstIndex << ", " << intMiddle << ", " << intLastIndex << endl;
}
if(boolFound) {
return intMiddle;
} else {
return -1;
}
}
int main() {
srand (time(NULL));
ofstream myfile;
myfile.open ("RandomNumber.txt");
if (myfile.is_open())
{
for (int i = 0; i < 1000; ++i)
{
int RandomNumbers = rand() % 1000 + 1;
myfile << RandomNumbers << "\n";
}
}
myfile.close();
int array_size = 1000;
int * array = new int[array_size];
int position = 0;
ifstream fin("RandomNumber.txt");
if(fin.is_open())
{
cout << "File opened!!! Loading array. ";
while(!fin.eof() && position < array_size)
{
fin >> array[position];
position++;
}
cout << "Displaying array..." << endl <<endl;
for(int intIndex = 0; intIndex < array_size; intIndex++)
{
cout << array[intIndex] << endl;
}
fin.close();
}
else
{
cout<< "File could not be opened." << endl;
}
cout << searchFull(array, array_size, 43) << endl;
cout << searchLinear(array, array_size, 43) << endl; //Incorrect not sorted
cout << searchFull(array, array_size, 5) << endl;
cout << searchLinear(array, array_size, 5) << endl; //Incorrect not sorted
sortBubble(array, array_size);
cout << searchFull(array, array_size, 43) << endl;
cout << searchLinear(array, array_size, 43) << endl;
cout << searchBinary(array, array_size, 43) << endl;
cout << searchFull(array, array_size, 5) << endl;
cout << searchLinear(array, array_size, 5) << endl;
cout << searchBinary(array, array_size, 5) << endl;
system("PAUSE");
return 0;
};
while(!fin.eof() is a blunder. What happens after the last value has been read, but before eof() occurs? (answer: You'll get the last entry copied twice). Fix it by going:
while ( position < array_size && fin >> array[position] )
position++;
Also, you should be displaying and sorting with position as the counter, not array_size.
Maybe your sortBubble function has a bug, or maybe it is just taking a long time to run. What happens if you try with 100 numbers? Can you post the code for it?
I have one more question, I want to add a _ in front of every Capital letter which will be converted to lowercase, plus the first letter cannot be capital!! I cant figure out how to do it... :{ example:
input: loLollL, output: lo_loll_l
and I want it to go backwards too: input: lo_loll_l output: loLollL
code is here:
#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
const int max = 100;
string slovo;
int pocet_r;
cout << "Zadaj pocet uloh:" << endl;
cin >> pocet_r;
if(pocet_r >= 1 && pocet_r <=100)
{
// funkcia na zabezpecenie minimalneho poctu chars
for (int i = 0; i <pocet_r; i++)
{
cout << "Uloha " << i+1 << ":" << endl;
cin >> slovo;
if(slovo.size() > max)
{
cout << "slovo musi mat minimalne 1 a maximalne 100 znakov" << endl;
}
while( slovo.size() > max)
{
cin >> slovo;
}
for (int i=0; i <= slovo.size(); i++)
{
int s = slovo[i];
while (s > 'A' && s <= 'Z')
{
if(s<='Z' && s>='A'){
return s-('Z'-'_z');
}else{
cout << "chyba";
}
}
}
cout << slovo[i] << endl;
}
}else{
cout << "Minimalne 1 a maximalne 100 uloh" << endl;
}
system("pause");
}
EDIT>
for (int i=0; i <= slovo.size(); i++)
{
while (slovo[i] >= 'A' && slovo[i] <= 'Z')
{
string s = transform(slovo[i]);
cout << s << endl;
s = untransform(s);
cout << s << endl;
}
}
This should work:
#include <string>
#include <cctype>
#include <iostream>
using namespace std;
string
transform(const string& s)
{
const size_t n = s.size();
string t;
for (size_t i = 0; i < n; ++i)
{
const char c = s[i];
if (isupper(c))
{
t.push_back('_');
}
t.push_back(tolower(c));
}
return t;
}
string
untransform(const string& s)
{
string t;
const size_t n = s.size();
size_t i = 0;
while (i < n)
{
char c = s[i++];
if (c != '_')
{
t.push_back(c);
continue;
}
c = s[i++];
t.push_back(toupper(c));
}
return t;
}
int
main()
{
string s = transform("loLollL");
cout << s << endl;
s = untransform(s);
cout << s << endl;
}