C++ Multi-Dimensional Array saving/loading to file error [closed] - c++

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 7 years ago.
Improve this question
I've been working on this C++ project for roughly 2 weeks now and I'm stumped on a couple things regarding 2D Arrays. To start off here is the code I wrote as of now:
http://pastebin.com/vCsz947Q
I decided to provide this as a pastebin link due to the fact that it's rather large (it uses 8 functions) and I thought it would save space in this post. I'm new to this site so I apologize if there's a better way that I'm not aware of.
The Problem:
When I go to save my "char seating" array to a .dat file using the "save seats" function that I created, I get a file that gives me the following garbage character " Ì " instead of the intended ' # ' (for open seats) or ' * ' (if a seat is bought).
My functions will save the intended amount of rows (15) and columns (30) despite this though. Also an asterisk will be placed when I go to "purchase a seat" in this program in the file. Additionally my program loads the files as intended, except for the fact that... Well... There's garbage data stored in the seat array.
I feel like this relates to another problem I'm having where if I go to the "purchase seats" function and I say to purchase a seat, it should replace a # with a *, but it doesn't, yet in the saved file it will show an asterisk in the intended spot... Which is very strange.
I have absolutely no idea why this occurs, and what's frustrating is this one thing that's preventing me from finishing this program. I want to believe that my original array in int main that's being called by other functions isn't being updated properly, but I don't know, which is why I came here to seek assistance.
Thank you for your assistance whoever can help.

Well for a start you have some undefined behaviour here inside your displaySeatingChart (char displaySeats[ ][30], float displayPrices[ ]) function with the following:
const int rowDisplay = 15;
const int colDisplay = 30;
as later within one of your loops you have
cout << displaySeats[rowDisplay][colDisplay];
which is clearly reading beyond the array bounds since in main() you define
const int rowMain = 15;
const int colMain = 30;
char seating[rowMain][colMain];
float seatPrices[15];
and pass both seating and seatPrices to the displaySeats function. There may well be other problems with your code but this at least is a clear example of undefined behaviour. Consider stepping through the code with a debugger to get a clearer idea of the source of the issue.
On another note given that you are working with C++ consider working with std::vector instead of arrays. This will give you more scope to ascertain the dimensions of the items that arrays that you are working with from within your utility functions and result in less potential for errors in array access.

Related

Expression must have a constant value error in an array with the size input by user [duplicate]

This question already has an answer here:
Passing an int to a function, then using that int to create an array
(1 answer)
Closed 4 years ago.
So i have this code, part of a larger function.
int size, j;
cout << "Enter the size of array" << endl;
cin >> size;
float b, n[size];// error
and I get the already famous E0028-expression must have a constant value. Now I saw people getting around this with "new int" and while I kinda understand the concept of it, technically I have not learned this type of int, not yet,nor objects etc. Also where I'm learning c++ they tell me that this should work just fine. I use visual studio enterprise 2017 to code(maybe there is a problem on my end with the compiler). Basically what I want is an array that has the size of it decided by the user input. And yes I know it wants to have a const and not a variable value. What are any work-arounds this ? (answer like you would try to teach your dog programming please because that is where my knowledge lies). Thank you.
Edit: While I see people trying to tell me use std::vector(that again i technically did not learn but kinda understand the concept of it) the people from the place where i'm learning c++ are telling me it should work that way.I did read a bit about the error before asking the question and saw some related stuff about the c99 standard( 2 much stuff to make a wall of text here). So the follow up question is: are they teaching outdated ways of writing this stuff ?
Thank you.
Variable length arrays, such as n[size], are not supported by standard C++, although some compilers allow it as an extension. (Note that C allows it, although it was made optional in C11.)
Use std::vector<float> n(size); in your case instead. That will allow you to access elements of n using []; e.g. n[0] is the first element.
As a rule of thumb, use a std::vector to model an array of a numeric type, unless you can think of a good reason not to.
The error is selfeplanatory: you cannnot use non-const expression in float n[size];.
In your case you need to use new operator or use one of standard containers: std::array or std::vector if you want to change the array size later on.

Designing Game of Life using classes C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
for my final project in my intro C++ class we have to design a version of Game of Life using classes and file I/O. I have been given some beginning functions/instructions but can't even begin to understand where to start or if I am missing other functions to get started. I've included the instructions given and what I have so far. I don't necessarily need the whole thing laid out for me, but if I could just have a little help on how to get started, that would be great.
Instructions:Since the project is in chapter 7, the book’s version doesn’t work with classes and it doesn’t have any file IO. Let’s
address the file IO first. On the project download page in addition to the usual items there will be two data files
containing very simple life community specifications. The files have the following format: first item in the file is the
number of rows the community requires, second item in the file is the number of columns the community requires, third
item is the LIFE community which is stored as ‘.’ (dead) or ‘O’ (alive) characters in the array shape specified by the
preceding two values.
In order for your project to work with these inputs you will need to specify a two dimensional array. The book specifies a
22 by 80 array. The GTA project uses a 50 by 100 (row by col) array. So long as your array is larger than the size specified
by the input, your code will work with the input. After creating the array, the code reads in the data from the input and
fills out your LIFE community array with a small twist. The book suggests filling in the grid directly with asterisks for live
cells and blanks for dead cells. We will use class objects instead.
The normal implementation of LIFE uses two identical arrays. One stores the now generation and one is used to store
the next generation. (see the book pgs 446 & 447) We will be using one array which contains LIFE cell objects made from
the simplest useful class we could think of. Our class objects will contain two Boolean data items that store the cell’s life
condition and one function which will age the cell.
Your LIFE community’s size should be square and an edge length is define globally as const int edge=#. Your class is
named cell and contains the public boolean variables aod_d0, aod_d1 and the void function age(). Create a general
function that counts the number of living neighbors of a cell and declare its type with the following declaration: int
nbors_sum(cell[edge][edge], int, int, int, int);. Your LIFE community ages a day at a time so create a general function that
reads cells at d0 and determines whether that cell is alive or dead (aod) at d1. It’s declaration is: void oneday(cell[edge]
[edge], int, int);. The oneday function will call the nbors_sum function. The GTA version has a fair amount of code in
main() including file input and the while(true) display loop.
Code:
#include <iostream>
#include <fstream>
using namespace std;
const int edge=20;
class cell{
public:
bool aod_d0, aod_d1;
int nbors_sum(cell[edge][edge],int,int,int,int);
void oneday(cell[edge][edge],int,int);
int main()
{
ifstream in;
in.open("glidergun.txt");
if(in.fail())
{
cout <<"Input file failed to open.\n";
return 1;
}
oneday()
in.close();
return 0;
}
void age();
int nbors_sum(cell[edge][edge],int,int,int,int);
void oneday(cell[edge][edge],int,int){
}
It's not so hard - that's a pretty common excercise, so there's a lot of material on the Web. Just check Wikipedia, for example, to get an idea and see some animations of this "Game" in motion:
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
As a starting point, I would suggest that you do the following:
Make your program read in a file and store the data within a 2D
array, as suggested by the excercise
Make your program print the
resulting 2D array to the console (standard output)
If you manage to get those two steps done, by the point you proceed you will already have a better understanding of what this is all about.
My general suggestion would be that you, if you face a problem like that where you don't know what to do, just start by doing the very obvious things that need to be done anyway (such as the reading the file, in this case). By doing that, you will get familiar with the rest on the way.

C++ Variables from external file using ifstream

I've written a program in VB which exports data into a text file, which I want to be read by another program in C++ and then that data be assigned as a variable. The program is essentially a quiz and the program I wrote in VB is question maker that exports all the data required into the text file.
Below is the text file:
test question|test A|test B|test C|test D|A|100|0|0|0|Right, I know this. The answer is 100% A. Good luck!|B|100|0|
From left to right we have, the question, AnswerA, AnswerB, AnswerC, AnswerD, the correct answer, percent 1, 2, 3, 4, (for polling an audience of what they think the answer may be) a friend's answer, a wrong answer (the program eliminates two wrong answers at one point, this answer is the remaining wrong answer) and percent 1 and 2 again (in case they eliminate 2 wrong answers but still want a poll).
I did quite a lot of google searching but found nothing to my following question (perhaps due to the fact I used the wrong keywords, I'm not too educated when it comes to programming jargon). What I want the C++ program to do is read the file and when it sees "|" it knows that what is coming is a new variable. Would I be better using ifstream or something else and how would I tell the program to identify the "|" and make it read whatever is in between as a variable?
Look at the documentation for istream::getline. You can use the | character as a delimiter.

C++ Running Code from file

This might seem a bit far fetched and possible off-topic (sorry if it is), but I'd like to know for sure if it is possible or not.
I am working on a Q and A program.
The text file is laid out in a Question tab Answer newline style.
My question is this: Is it possible to read an answer as a function.
Example:
Question - What time is it? / Answer - getCurrentTime()
Question - What is today's date? / Answer - getCurrentDate()
Then the program, though string parsing, knows that this is a function without an argument and calls the function getCurrentTime() or getCurrentDate() which prints the time or date respectively.
This is possible using an array of function pointers. You just load all the functions into the array. How you obtain the correct index is up to you. The only useful way I can come up with is maintain a second array containing the function names in the same positions as the functions in the function array. Then search the function name array and use the index in that array to access the correct function in the function array. If you need a better explanation leave a message. It is very late at night here and I need to work in the morning.
Barmar's solution will work to and is the better way to go about it but use function pointers.
Hope this helps
dannyhut

Simple General Questions about C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Ive moved from autoit and am now learning C++ and some problems keep coming up.
The first one is storing character input. The problem is that I have no idea how many characters are in that line of the file (if you are reading a file) or how many letters a user is going to type (in a console application).
What is the best way to approach this problem?? I have heard about the string class, but I want to avoid it becuase I dont know how it works and that leads to vunerabilities etc.
Secondly...
In C you can load shellcode into memory, create a function pointer, and execute that code.
Is there any mechanism for this in C++???
Thirdly...
How does the interpreter iterate through char arrays for string output??? (char array[3];) Does the compiler keep track of the size of the array, or does it just keep reading from memory until it hits that \0 thing???
Lastly...
If Char * are just pointers to data in memory, then why does:
char * title = "Program Title";
this work??? where is the string literal stored in memory?? how is it referenced???
Thankyou very much. I greatly appreciate your help.
-Hyperzap
Investing your time in learning std::string is well worth the effort, as it takes care of a lot of hassle for you. If you don't want to take advantage of the features in C++, then why use C++ and not just C?
You can use the same code for this as you would in C.
Yes, iostream-output of C-style strings outputs until terminating zero. Once again, if you use std::string you do not have to care about such details.
Correct me if I'm wrong, but I think title would be a const char[] stored on the stack.
Example:
const char* hello = "Hello\0World";
cout << hello; // Prints only "Hello", i.e. up to terminating zero (\0)
The reason this works:
const char* hello = "Hello world";
cout << hello;
is because hello is really "Hello world\0"; - in other words, the compiler inserts a terminating zero.
Note that std::string doesn't do any magic. It too reads until the terminating zero:
string hello = "Hello\0World\n";
cout << hello; // Still only gives "Hello"
char* title = "String Literal" works because the compiler preallocates a memory location to store your string literal, thus you then get back a pointer to this memory location.
In c++, an array for which you know the size at compile time (as in your example: char array[3] is a type in itself, so the compiler does keep track of the size. However, if you do not know the size (ie. char array[]), it is just a pointer to char. However, you should be using std::vector in c++ (better safety and performance).
I'm not too sure about your other two questions (didn't quite understand them)