How can I display this Sokoban board? - c++

I'm new here, and I have a basic level of programming, and the problem is that I've been trying to display this Sokoban board for a week, and I don't know what to do anymore.
As I'm new here and I don't know very well how this forum works, I show you the part of my program that I consider important.
bool loadLevel(ifstream &file, tSokoban &sokoban, int level) { //Falta leer el nivel hasta que vuelva a leer Level
tGame game;
bool found = false;
string line;
int index, x = 0;
game.sokoban.ncol = 0;
game.sokoban.nrows = 0;
file >> line;
while (!file.eof())
{
if (line == "Level")
{
file >> index;
if (index == level)
{
found = true;
}
}
while (found && !file.eof())
{
if (found)
{
getline(file, line);//File reads "" , so I put it again so the program works
getline(file, line);
if (line.length() > game.sokoban.ncol)
{
game.sokoban.ncol = line.length();
}
for (int i = 0; i < line.size(); i++)
{
switch (line[i])
{
case '#':
sokoban.board[x][i] = Wall;
break;
case ' ':
sokoban.board[x][i] = Free;
break;
case '.':
sokoban.board[x][i] = GoalFree;
break;
case '*':
sokoban.board[x][i] = GoalBox;
break;
case '+':
sokoban.board[x][i] = GoalPlayer;
break;
case '#':
sokoban.board[x][i] = Player;
game.sokoban.playerX = x;
game.sokoban.playerY = i;
break;
case '$':
sokoban.board[x][i] = Box;
sokoban.boxCount++;
break;
}
}
x++;
sokoban.nrows++;
getline(file, line);
}
else
{
cout << "Could not find the level you were looking for..." << endl;
}
}
}
return found;
}
void draw(const tGame &game){
system("cls");
cout << "File: " << game.fileName << endl;
cout << "Level " << game.curLevel << endl;
cout << endl;
cout << endl;
for (int i = 0; i < game.sokoban.ncol; i++)
{
for (int f = 0; f < game.sokoban.nrows; f++)
{
drawTile(game.sokoban.board[i][f]);
}
cout << endl;
}
cout << game.numMoves;
}
void drawTile(tTile tile){
switch (tile)
{
case Free:
backgroundColor(1);
cout << " ";
break;
case Wall:
backgroundColor(3);
cout << " ";
break;
case GoalFree:
backgroundColor(7);
cout << "..";
break;
case GoalBox:
backgroundColor(8);
cout << "**";
break;
case GoalPlayer:
backgroundColor(11);
cout << "++";
break;
case Player:
backgroundColor(11);
cout << "00";
break;
case Box:
backgroundColor(13);
cout << "()";
break;
}
}
My file just contains one level, which is in this format:
Level 0
###################
##### ###########
#####$ ###########
##### $###########
### $ $ ##########
### # ## ##########
# # ## ##### ..#
# $ $ ..#
##### ### #### ..#
##### #########
###################
The problem is that when the program reads the file and has to display its contents, it just doesn't, and I don't know where the problem is, so I'm desperate now. If anyone could help me with this I would appreciate it very much :). Thank you all.

Related

Read Binary File. String after convert from char array with size of 3 has a size of 4

I have a strange problem. I don't even know if it's the code. When reading a binary file, two consecutive strings with length 3 have to be read and stored. I do this with a char array. This is then simply set to the string variable.
Strange is that with the first string at the end always an F is appended and with the second not.
Console output
In the console output you can see that the string has a length of 4 at the first mark. The second one has a length of 3.
The strange thing is that the creation and reading of both strings from the binary file were handled with the same procedure in the code and that in the first one an F is always appended.
Here is the code places with which the part in the binary file is read. It is the variable fromDestination in case 'F'.
switch (type ) {
case 'F':
for(size_t i = 0; i < sizeof(aFromDestination); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aFromDestination[i]),sizeof(char));
}
//aFromDestination[3] = '\0';
fromDestination = aFromDestination;
aFromDestination[0] = 0;
break;
case 'R':
for(size_t i = 0; i < sizeof(aPickupLocation); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aPickupLocation[i]),sizeof(char));
}
pickupLocation = aPickupLocation;
aPickupLocation[0] = 0;
break;
case 'H':
for(size_t i = 0; i < sizeof(aHotel); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aHotel[i]),sizeof(char));
}
hotel = aHotel;
aHotel[0] = 0;
break;
}
travelagency.cpp
#include "travelagency.h"
#include "flightbooking.h"
#include "hotelbooking.h"
#include "rentalcarreservation.h"
TravelAgency::TravelAgency()
{
}
void TravelAgency::readFile()
{
int countFlights = 0, countRents = 0, countHotels = 0;
double allFlightsCosts = 0, allRentCosts = 0, allHotelCosts = 0;
std::string zeile;
std::string fileName = "bookings.txt";
std::ifstream inputFilestream;
inputFilestream.open(fileName.c_str(), std::ifstream::in);
if (!inputFilestream.is_open())
std::cerr << "Datei konnte nicht geoeffnet werden" << std::endl;
while(!inputFilestream.eof()) {
types type;
std::stringstream zeileStringStream;
std::string fromDate, toDate, pickupLocation, returnLocation, company, hotel, town, fromDestination, toDestination, airline;
unsigned int id;
double price;
int numberOfAttribute = 1, countFields = 0, numberOfLine = 1;
getline(inputFilestream, zeile);
zeileStringStream << zeile;
for(auto &k : zeile) {
if(k == '|') {
numberOfAttribute++;
}
}
while(!zeileStringStream.eof()) {
std::string attribute;
switch (countFields) {
case 0: {
getline(zeileStringStream, attribute, '|');
for(char character : attribute) {
switch (character) {
case 'F': {
type = Flight;
}
break;
case 'R': {
type = Rent;
}
break;
case 'H': {
type = Hotel;
}
break;
}
}
break;
}
case 1: {
getline(zeileStringStream, attribute, '|');
id = stoi(attribute);
break;
}
case 2: {
getline(zeileStringStream, attribute, '|');
price = stod(attribute);
break;
}
case 3: {
getline(zeileStringStream, fromDate, '|');
break;
}
case 4: {
getline(zeileStringStream, toDate, '|');
break;
}
case 5: {
switch (type) {
case Flight:
getline(zeileStringStream, fromDestination, '|');
break;
case Rent:
getline(zeileStringStream, pickupLocation, '|');
break;
case Hotel:
getline(zeileStringStream, hotel, '|');
break;
}
break;
}
case 6: {
switch (type) {
case Flight:
getline(zeileStringStream, toDestination, '|');
break;
case Rent:
getline(zeileStringStream, returnLocation, '|');
break;
case Hotel:
getline(zeileStringStream, town); //end of the line. Fehler bei der ausgabe.
break;
}
break;
}
case 7: {
switch (type) {
case Flight:
getline(zeileStringStream, airline); //end of the line. Fehler bei der ausgabe.
break;
case Rent:
getline(zeileStringStream, company); //end of the line. Fehler bei der ausgabe.
break;
default:
break;
}
break;
}
}
countFields++;
}
switch (type) { //obejekte erstellen und speichern
case Flight: {
FlightBooking *f = new FlightBooking(id, price, fromDate, fromDestination, toDestination, airline);
bookings.push_back(f);
allFlightsCosts += price;
countFlights++;
break;
}
case Rent: {
RentalCarReservation *r = new RentalCarReservation(id, price, fromDate, toDate, pickupLocation, returnLocation, company);
bookings.push_back(r);
allRentCosts += price;
countRents++;
break;
}
case Hotel: {
HotelBooking *h = new HotelBooking(id, price, fromDate, toDate, hotel, town);
bookings.push_back(h);
allHotelCosts += price;
countHotels++;
break;
}
}
numberOfLine++;
}
inputFilestream.close();
std::cout << "Es wurden " << countFlights << " Flugbuchungen im Wert von " << allFlightsCosts << "," << std::endl;
std::cout << countRents << " Mietwagenbuchungen im Wert von " << allRentCosts << " und" << std::endl;
std::cout << countHotels << " Hotelreservierungen im Wert von " << allHotelCosts << " eingelesen." << std::endl;
}
void TravelAgency::readBinaryFile()
{
int countFlights = 0, countRents = 0, countHotels = 0;
double allFlightsCosts = 0.0, allRentCosts = 0.0, allHotelCosts = 0;
char type;
char aFromDestination[3], aToDestination[3];
char aFromDate[8], aToDate[8];
char aHotel[15], aTown[15], aAirline[15], aCompany[15], aPickupLocation[15], aReturnLocation[15];
std::string fromDate, toDate, pickupLocation, returnLocation, company, hotel, town, fromDestination, toDestination, airline;
long id;
double price;
std::string inputFileName = "bookingsBinary.bin";
std::ifstream inputFileStream;
inputFileStream.open(inputFileName.c_str(),std::ifstream::binary | std::ifstream::in);
if(!inputFileStream) {
std::cerr << inputFileName << " kann nicht geoeffnet werden!" << std::endl;
}
do{
//fall 1
inputFileStream.read(reinterpret_cast<char*>(&type), sizeof(char));
//fall 2
inputFileStream.read(reinterpret_cast<char*>(&id),sizeof(long));
//fall 3
inputFileStream.read(reinterpret_cast<char*>(&price),sizeof(double));
//fall4
for(size_t i = 0; i < sizeof(aFromDate); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aFromDate[i]),sizeof(char));
}
fromDate = aFromDate;
aFromDate[0] = 0;
//fall 5
for(size_t i = 0; i < sizeof(aToDate); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aToDate[i]),sizeof(char));
}
toDate = aToDate;
aToDate[0] = 0;
//fall6
switch (type ) {
case 'F':
for(size_t i = 0; i < sizeof(aFromDestination); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aFromDestination[i]),sizeof(char));
}
//aFromDestination[3] = '\0';
fromDestination = aFromDestination;
aFromDestination[0] = 0;
break;
case 'R':
for(size_t i = 0; i < sizeof(aPickupLocation); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aPickupLocation[i]),sizeof(char));
}
pickupLocation = aPickupLocation;
aPickupLocation[0] = 0;
break;
case 'H':
for(size_t i = 0; i < sizeof(aHotel); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aHotel[i]),sizeof(char));
}
hotel = aHotel;
aHotel[0] = 0;
break;
}
//fall7
switch (type) {
case 'F':
for(size_t i = 0; i < sizeof(aToDestination); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aToDestination[i]),sizeof(char));
}
toDestination = aToDestination;
aToDestination[0] = 0;
break;
case 'R':
for(size_t i = 0; i < sizeof(aReturnLocation); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aReturnLocation[i]),sizeof(char));
}
returnLocation = aReturnLocation;
aReturnLocation[0] = 0;
break;
case 'H':
for(size_t i = 0; i < sizeof(aTown); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aTown[i]),sizeof(char));
}
town = aTown;
aTown[0] = 0;
break;
}
//fall8
switch (type) {
case 'F':
for(size_t i = 0; i < sizeof(aAirline); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aAirline[i]),sizeof(char));
}
airline = aAirline;
aAirline[0] = 0;
break;
case 'R':
for(size_t i = 0; i < sizeof(aCompany); i++) {
inputFileStream.read(reinterpret_cast<char*>(&aCompany[i]),sizeof(char));
}
company = aCompany;
aCompany[0] = 0;
break;
}
switch (type) { //obejekte erstellen und speichern
case 'F': {
FlightBooking *f = new FlightBooking(id, price, fromDate, fromDestination, toDestination, airline);
bookings.push_back(f);
allFlightsCosts += price;
countFlights++;
}
break;
case 'R': {
RentalCarReservation *r = new RentalCarReservation(id, price, fromDate, toDate, pickupLocation, returnLocation, company);
bookings.push_back(r);
allRentCosts += price;
countRents++;
}
break;
case 'H': {
HotelBooking *h = new HotelBooking(id, price, fromDate, toDate, hotel, town);
bookings.push_back(h);
allHotelCosts += price;
countHotels++;
}
break;
}
}while (!inputFileStream.eof());
inputFileStream.close();
std::cout << "Es wurden " << countFlights << " Flugbuchungen im Wert von " << allFlightsCosts << "," << std::endl;
std::cout << countRents << " Mietwagenbuchungen im Wert von " << allRentCosts << " und" << std::endl;
std::cout << countHotels << " Hotelreservierungen im Wert von " << allHotelCosts << " eingelesen." << std::endl;
}
void TravelAgency::showAllBookings() const
{
for (auto &k : bookings) {
std::cout << k->showDetails() << std::endl;
}
//showExpensiveBooking();
}
void TravelAgency::showExpensiveBooking() const
{
int price;
int highesPrice = 0;
int place;
for(size_t i = 0; i < bookings.size(); i++) {
price = bookings.at(i)->getPrice();
if (price > highesPrice) {
highesPrice = price;
place = i;
}
}
std::cout << "Hoechster Preis: " << std::endl;
bookings.at(place)->showDetails();
}
`
I thought it would work to make the char array to length 4 and then shorten it to position 3 after filling.

How to read txt files into an array that are stored into class variables? [duplicate]

This question already has answers here:
Reading file into array of struct c++
(3 answers)
C++ Reading text file with delimiter into struct array
(2 answers)
C++ Reading data from text file into array of structures
(2 answers)
How do I read data from a text file into an array of struct
(1 answer)
Reading data from a text file into an array of structs
(1 answer)
Closed 2 years ago.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class BasketballPlayer
{
public:
void printBasketballPlayer() const;
BasketballPlayer(); //Constructor with Parameters
private:
string name;
float MinutesPlayed;
float PlayerScoreEffRating;
float Steals;
float AST;
float PointPerGame;
float Rebounds;
float FieldGoal;
float FreeThrow;
float ThreePointers;
float BLK;
float TurnOver;
};
class BasketballTeam
{
public:
string name;
void printBasketballTeam() const;
bool findPlayer(string &);
void editPlayer(bool&);
BasketballTeam(); //Default Constructor
void getName()
{
getline(cin, name);
}
private:
//void BasketballPlayer();
string name;
float MinutesPlayed;
float PlayerScoreEffRating;
float Steals;
float AST;
float PointPerGame;
float Rebounds;
float FieldGoal;
float FreeThrow;
float ThreePointers;
float BLK;
float TurnOver;
string myArray[16][11];
string PlayerName[15];
float myArray[15][11];
void Team()
{
ifstream file("TextFileTeam.txt");
if (file.is_open())
{
string myArray[16];
for (int i = 0; i < 16; ++i)
{
file >> myArray[i];
}
}
}
};
int main()
{
BasketballPlayer Play;
string Search;
bool isPlayerThere;
char Change;
BasketballTeam Team;
cout << " Welcome to the Brooklyn Net's Stats and DataBase " << endl;
cout << " These are the stats of our new SuperStar " << endl;
Play.printBasketballPlayer();
cout << " < Would you Like to Update stats of the roster > --> Y or --> N " << endl;
cin >> Change;
cout << endl;
if (Change == 'Y' || 'y')
{
Team.findPlayer(Search);
Team.editPlayer(isPlayerThere);
}
else
{
Team.printBasketballTeam();
}
Team.printBasketballTeam();
return 0;
}//end main
void BasketballPlayer::printBasketballPlayer() const
{
cout << "|| The players name || " << this->name;
cout << endl;
cout << "|| Minutes Per Game || " << this->MinutesPlayed;
cout << endl;
cout << "|| Turnovers Per Game || " << this->TurnOver;
cout << endl;
cout << "|| Points Per Game || " << this->PointPerGame;
cout << endl;
cout << "|| Rebounds Per Game || " << this->Rebounds;
cout << endl;
cout << "|| Asists Per Game || " << this->AST;
cout << endl;
cout << "|| Blocks Per Game || " << this->BLK;
cout << endl;
cout << "|| 3 Point % || " << this->ThreePointers;
cout << endl;
cout << "|| Free-Throw % || " << this->FreeThrow;
cout << endl;
cout << "|| Field Goal %|| " << this->FieldGoal;
cout << endl;
cout << "|| Steals % || " << this->Steals;
cout << endl;
cout << "|| Player Scoreing Effiencey Rating || " << this->PlayerScoreEffRating;
cout << endl;
}
BasketballPlayer::BasketballPlayer() //Constructor with Parameters
{
name = "James Harden";
MinutesPlayed = 40.2f;
TurnOver = 4.2f;
PointPerGame = 24.1f;
Rebounds = 8.1f;
AST = 12.0f;
BLK = 0.6f;
ThreePointers = 37.9f;
FreeThrow = 89.2f;
FieldGoal = 48.2f;
Steals = 1.1f;
PlayerScoreEffRating = 1.561f;
}
void BasketballTeam::printBasketballTeam() const
{
ifstream file("TextFileTeam.txt");
if (file.is_open())
{
string myArray[16];
for (int i = 0; i < 16; ++i)
{
file >> myArray[i];
cout << myArray[i];
cout << endl;
}
}
}
bool BasketballTeam::findPlayer(string&)
{
bool Finder = false;
const char *name;
switch (*name)
{
case 1:
if(name == "Kevin_Durant")
Finder = true;
break;
case 2:
if (name == "Kyrie_Irving")
Finder = true;
break;
case 3:
if (name == "James_Harden")
Finder = true;
break;
case 4:
if (name == "Joe_Harris")
Finder = true;
break;
case 5:
if (name == "Jarrett_Allen")
Finder = true;
break;
case 6:
if (name == "Jeff_Green")
Finder = true;
break;
case 7:
if (name == "Taurean_Prince")
Finder = true;
break;
case 8:
if (name == "Timothe_Luwawu - Cabarrot")
Finder = true;
break;
case 9:
if (name == "Spencer_Dinwiddie")
Finder = true;
break;
case 10:
if (name == "DeAndre_Jordan")
Finder = true;
break;
case 11:
if (name == "Bruce_Brown_Jr.")
Finder = true;
break;
case 12:
if (name == "Landry_Shamet")
Finder = true;
break;
case 13:
if (name == "Chris_Chiozza")
Finder = true;
break;
case 14:
if (name == "Reggie_Perry")
Finder = true;
break;
case 15:
if (name == "Tyler_Johnson")
Finder = true;
break;
default:
cout << " Player not in Roster " << endl;
break;
}
return Finder;
}
void BasketballTeam::editPlayer(bool &)
{
int editValue;
BasketballTeam Team;
bool isThere;
ifstream file("JustData.txt");
if (file.is_open())
{
string myArray[15];
for (int i = 0; i < 15; ++i)
{
file >> myArray[i];
}
}
if (isThere == true)
{
cout << " What would you like to edit? " << endl;
cout << "[1] Mintues, [2] Turnover, [3] Points Per Game, [4] Rebounds Per Game, [5]
Steals Per
Game, [6] Free Throw %, [7] Assits Per Game, [8] Filed Goal %" << endl;
cout << "[7] Assits Per Game, [8] Filed Goal %[9] 3P%, [10] Player Scoring Eff, [11]
Blocks Per Game ---> ";
cin >> editValue;
switch (editValue)
{
case 1:
MinutesPlayed = editValue;
break;
case 2:
PlayerScoreEffRating = editValue;
break;
case 3:
PointPerGame = editValue;
break;
case 4:
Rebounds = editValue;
break;
case 5:
Steals = editValue;
break;
case 6:
FreeThrow = editValue;
break;
case 7:
AST = editValue;
break;
case 8:
FieldGoal = editValue;
break;
case 9:
ThreePointers = editValue;
break;
case 10:
PlayerScoreEffRating = editValue;
break;
case 11:
BLK = editValue;
break;
default:
break;
}
}
}
BasketballTeam::BasketballTeam() //Default Constructor
{
int j;
int row;
int col;
j = 0;
ifstream file("JustData.txt");
if (file.is_open())
{
float PlayerArray[15][11];
for (int row = 0; row < 15; row++)
{
for (int col = 0; col < 11; col++)
{
file >> PlayerArray[row][col];
MinutesPlayed = PlayerArray[j][col];
TurnOver = PlayerArray[j][col];
Rebounds = PlayerArray[j][col];
PointPerGame = PlayerArray[j][col];
AST = PlayerArray[j][col];
BLK = PlayerArray[j][col];
ThreePointers = PlayerArray[j][col];
FreeThrow = PlayerArray[j][col];
FieldGoal = PlayerArray[j][col];
Steals = PlayerArray[j][col];
PlayerScoreEffRating = PlayerArray[j][col];
j++;
}
}
}
ifstream file2("JustNames.txt");
if (file2.is_open())
{
string PlayerName[15];
for (int row = 0; row < 15; row++)
{
file >> PlayerName[row];
name = PlayerName[row];
}
}
};
JustData.txt
36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575
35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403
40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561
31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361
26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062
25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519
18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311
19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091
21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25
20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813
17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329
17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14
11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821
10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98
6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9
JustNames.txt
Kevin_Durant
Kyrie_Irving
James_Harden
Joe_Harris
Jarrett_Allen
Jeff_Green
Taurean_Prince
Timothe_Luwawu-Cabarrot
Spencer_Dinwiddie
DeAndre_Jordan
Bruce_Brown_Jr.
Landry_Shamet
Chris_Chiozza
Reggie_Perry
Tyler_Johnson
TeamNoTitle.txt
Kevin_Durant,36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575
Kyrie_Irving,35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403
James_Harden,40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561
Joe_Harris,31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361
Jarrett_Allen,26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062
Jeff_Green,25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519
Taurean_Prince,18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311
Timothe_Luwawu-Cabarrot,19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091
Spencer_Dinwiddie,21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25
DeAndre_Jordan,20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813
Bruce_Brown_Jr.,17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329
Landry_Shamet,17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14
Chris_Chiozza,11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821
Reggie_Perry,10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98
Tyler_Johnson,6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9
TeamFileNets.txt
Player,MPG,TOV,RPG,APG,SPG,BPG,PPG,FG%,3P%,FT%,SC-EFF
Kevin_Durant,36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575
Kyrie_Irving,35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403
James_Harden,40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561
Joe_Harris,31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361
Jarrett_Allen,26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062
Jeff_Green,25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519
Taurean_Prince,18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311
Timothe_Luwawu-Cabarrot,19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091
Spencer_Dinwiddie,21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25
DeAndre_Jordan,20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813
"Bruce_Brown_Jr.",17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329
Landry_Shamet,17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14
Chris_Chiozza,11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821
Reggie_Perry,10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98
Tyler_Johnson,6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9
I'm sure that I'm not understanding Classes. Trying to use fstream to hold data of players so that my classes and driver code can change those files then display data from stored data in classes. I have no syntax errors but code not running. Most likey because of me reading file into array wrong to get data into my classes from file and improper calling of classes in main function.

Switch cases and getch() don't work together

I've done a pretty simple switch where if I press a character, the integer of it adds one to itself and prints a message, it worked pretty fine with the "cin>>" and the "getchar()", but when I added the getch, It still prints the message but it stops updating the integer "how I know"? cause I made a random value that the integer has to get to, and it's between 1 and 20, and with the getch it simply goes on without stopping itself when arrived to the value
'''
void Journ(char const *bypassto = "x")
{
int m = 4;
int VAL[m];
for (int j=0; j<m; j++)
{
VAL[j] = rand()%20 + 1;
}
char comm;
int W;
int A;
int S;
int D;
char journkey;
if (bypassto != "x" ) {
journkey = *bypassto;
} else {
cout << "Choose a direction: \n";
cout <<"[FOWARD]-[LEFT]-[RIGHT]-[BACKWARDS]\n";
cout << "w for foward - a for left - d for right - s for backwards \n";
}
while (comm!=4)
{
// cin >> comm;
comm = getch();
switch(comm)
{
case 'w':
{
cout << "You went foward. \n";
W++;
break;
}
case 'a':
{
cout << "You went left. \n";
A++;
break;
}
case 's':
{
cout << "You went backwards. \n";
S++;
break;
}
case 'd':
{
cout << "You went right. \n";
D++;
break;
}
}
if(W == VAL[0])
{
BattleIntro();
break;
}
else if(A == VAL[1])
{
BattleIntro();
break;
}
else if(S == VAL[2])
{
BattleIntro();
break;
}
else if(D == VAL[3])
{
BattleIntro();
break;
}
}
}
'''

Variable changing value and unsure of why

So I'm still fairly new to c++ and programming in general, but I'd like to assume that I have a fairly good grasp of the concept and control flow (possibly lol). I'm currently creating a top down style game that allows the user to interact with the inventory of a chest. The problem that has me extremely confused is that I modify a variable but then it changes to something entirely different after "updating" the console.
Interactive chest inventory displaying 10 gold
After pressing s to update the console
The gold amount in the chest is set to 10 in the chestLoot() function, but is then changed to a value of 303, which is the macro for the Healing potion. Why is the chest.gold value being changed to 303 after I set it to 10? Any help on this would be much appreciated. (Don't be too harsh, I'm still new to stack overflow and c++ as well as programming in general)
Here is the code that handles the chest inventory as well as the loot that is generated:
void chestLoot(int x)
{
switch (tutorial.chestIt)
{
case 0:
chest.inventory[x] = WOODEN_SWORD_ID;
break;
case 1:
chest.inventory[x] = GOLD_ID;
chest.gold = 10;
break;
case 2:
chest.inventory[x] = HEALING_POTION_ID;
break;
case 3:
chest.inventory[x] = LEATHER_HELMET_ID;
break;
}
tutorial.chestIt++;
}
void chestInventory()
{
bool endLoop = false;
int x = 0;
int selection = 0;
int highlighted = 0;
while (endLoop == false)
{
system("cls");
std::cout << "Chest:" << std::endl << std::endl;
if (tutorial.gridChestOpened == false)
updatePlayer(5);
for (x = 0; x <= player.level + 3; x++)
{
if (tutorial.gridChestOpened == false)
{
chestLoot(x);
}
switch (chest.inventory[x])
{
case WOODEN_SWORD_ID:
std::cout << x + 1 << ". ";
if (selection == x)
{
std::cout << "- ";
highlighted = selection;
}
std::cout << "Wooden Sword";
break;
case GOLD_ID:
std::cout << x + 1 << ". ";
if (selection == x)
{
std::cout << "- ";
highlighted = selection;
}
std::cout << chest.gold << " Gold";
break;
case HEALING_POTION_ID:
std::cout << x + 1 << ". ";
if (selection == x)
{
std::cout << "- ";
highlighted = selection;
}
std::cout << "Healing Potion";
break;
case LEATHER_HELMET_ID:
std::cout << x + 1 << ". ";
if (selection == x)
{
std::cout << "- ";
highlighted = selection;
}
std::cout << "Leather Helmet";
break;
case NULL:
break;
}
std::cout << std::endl;
}
tutorial.gridChestOpened = true;
switch (_getch())
{
case 'w':
--selection;
if (selection < 0)
selection = 0;
if (chest.inventory[selection] == NULL)
++selection;
break;
case 's':
++selection;
if (selection > tutorial.chestIt)
selection = tutorial.chestIt;
if (chest.inventory[selection] == NULL)
--selection;
break;
case 'e':
if (chest.inventory[highlighted] == 0)
{
std::cout << "There is nothing there";
break;
}
else if (chest.inventory[highlighted] == GOLD_ID)
{
player.gold = player.gold + chest.gold;
chest.inventory[highlighted] = NULL;
break;
}
else
{
for (int y = 1; y <= player.level + 9; y++)
{
if (player.inventory[y] == NULL)
{
player.inventory[y] = chest.inventory[highlighted];
chest.inventory[highlighted] = NULL;
}
}
}
break;
case 27:
endLoop = true;
drawScreen(NULL);
break;
}
}
}
Here are the global variables that are used in the function:
struct Loot
{
int inventory[2];
int gold;
}chest, pot;
struct Entity
{
int position[2] = { 2, 2 };
int gold = 0;
int health = 10;
int level = 1;
int totalXp = 0;
int inventory[11];
int mainHand[2] = {/*location, item*/};
}player/*enemy*/;
struct Grid
{
int grid[6][12] = {
{1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,1,1,1,1,1},
{1,0,0,0,0,2,0,1,0,0,3,1},
{1,0,2,0,0,0,0,1,0,0,0,1},
{1,0,0,0,0,2,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,4,1}
};
bool gridChestOpened = false;
int chestIt = 0;
}tutorial;
// Item ID's
#define WOODEN_SWORD_ID 301
#define GOLD_ID 302
#define HEALING_POTION_ID 303
#define LEATHER_HELMET_ID 304
Any tips on improving my code are much appreciated as well :)
2: Check HerePassing a variable from one function to another
Your problem is that the member inventory of Loot is not dimensioned properly. The only valid values for x in chest.invetory[x] are 0 and 1. Your code is however clearly writing to chest.inventory[2], for example when you call chestLoot(2).
The memory in a struct is laid out sequentially, so chest.inventory[2] = HEALING_POTION_ID; will quietly overwrite the next 4 bytes after the chest.inventory[1] which is chest.gold;
Well, the inventory member of your "loot" struct is an array of ints of length 2. But you seem to be calling "chestLoot" with a value greater than 1. This is causing you to go off the end of your array and write to where "gold" should be.

How can I loop a switch statement to check re-check a char? (C++)

I want to make sure that the user enters either 'A','B','C' or 'D' in the default, but if they don't, have them re-enter a character until it matches one of the 4 characters listed above. How can I loop a switch statement to ensure that they've made a proper choice?
cout << "Enter the seat that you'd like to place the passenger in: "; cin >> aisle;
aisle = toupper(aisle);
switch (aisle){
case 'A':
temp = 0;
break;
case 'B':
temp = 1;
break;
case 'C':
temp = 2;
break;
case 'D':
temp = 3;
break;
default:
cout << "Input error, please re-enter an aisle: "; cin >> aisle;
aisle = toupper(aisle);
break;
}
Temp is my method of converting the character to an index value to refer to an array.
I would set a flag in the default case and put the whole thing into a do-while loop, like this:
bool tryAgain = false;
do
{
cout << "Enter the seat that you'd like to place the passenger in: "; cin >> aisle;
aisle = toupper(aisle);
switch (aisle){
case 'A':
temp = 0;
break;
case 'B':
temp = 1;
break;
case 'C':
temp = 2;
break;
case 'D':
temp = 3;
break;
default:
cout << "Input error, please re-enter an aisle (A, B, C, or D)";
tryAgain = true;
break;
}
}
while (tryAgain);
You can do it without the switch statement. For example
#include <cstring>
//...
int temp = -1;
cout << "Enter the seat that you'd like to place the passenger in: ";
do
{
cin >> aisle;
aisle = toupper(aisle);
const char *seats = "ABCD";
const char *p = strchr( seats, aisle );
temp = ( p == NULL ? -1 : p - seats );
if ( temp == -1 )
{
cout << "Input error, please re-enter an aisle: ";
}
} while ( temp == -1 );
Use a while loop around the switch statement.
while ( true )
{
bool breakLoop = true;
cout << "Enter the seat that you'd like to place the passenger in: ";
cin >> aisle;
aisle = toupper(aisle);
switch (aisle){
case 'A':
temp = 0;
break;
case 'B':
temp = 1;
break;
case 'C':
temp = 2;
break;
case 'D':
temp = 3;
break;
default:
cout << "Input error.";
breakLoop = false;
}
if ( breakLoop )
{
break;
}
}
You can use goto statement if you want, something like this :
retry:
cout << "Enter the seat that you'd like to place the passenger in: ";
cin >> aisle;
aisle = toupper(aisle);
switch (aisle){
case 'A':
temp = 0;
break;
case 'B':
temp = 1;
break;
case 'C':
temp = 2;
break;
case 'D':
temp = 3;
break;
default:
cout << "Invalid input, please try again. " << endl;
goto retry;
break;
}
I would not recommend to use goto if your script is a bit lengthy.
You tagged this as C++ and used std::cin. Perhaps you should consider std::strings.
In C++:
int retVal = -1;
// for simplicity during development, I use ss for input
std::stringstream ss;
ss << "53d"; // change test sequence here
std::cout << "Enter seat you'd like to place the passenger in: ";
char aisle;
do
{
ss >> aisle; // use ss instead of cin for development
// for development, echo user inputs,
// but remove the following before release
std::cout << " " << aisle << std::endl;
// toupper returns an int, but aisle is char
aisle = static_cast<char>(toupper(aisle));
const std::string Seats = "ABCD";
size_t indx = Seats.find(aisle);
if(indx != std::string::npos) // found aisle in Seats
{
retVal = aisle - 'A'; // return 0, 1, 2, or 3
break; // found - aisle is in range
}
std::cout << "Input error, please re-enter an aisle: ";
} while(true);
std::cout << "aisle: " << aisle << " retVal: " << retVal << std::endl;