I feel like I'm missing something. I'm working on a basic simulator for school and I've been playing with fscanf() as a way to read an ini file. I know there is libraries for this type of thing but I am having a problem with fscanf() regardless.
#ifndef _BUILDING
#define _BUILDING
#include<stdio.h>
class building{
private:
//building parts
//ini file [world]
char outfile[25];
int floors;
int elevators;
int workersPerFl;
int startWork[2];
int startCust[2];
int endWork[2];
int endCust[2];
//[customer]
int inwPerHr;
int changePerHr;
int toFirstFl;
public:
building();
};
The code in question.
needed info: floors is type int and outfile is a char[25]
The goal is to pull everything from the file to the building class and then use that to initialize the simulator controllers/AI. I keep getting an error when it tries to write to floors.
test.cc:10:54: warning: format specifies type 'int *' but the argument has type
'int' [-Wformat]
fscanf(fpt, "%*s %*s %*s %24s %*s %*s %i", outfile, floors);
~~ ^~~~~~
(unrelated to this error, but I changed that %s to %24s because you said outfile was char[25]: any naked %s is a buffer overflow waiting to happen)
Unhandled exception at 0x77da15de in Elevator_Sim_GSP_321_Howard.exe: 0xC0000005: Access violation writing location 0xcccccccc.
I had read if you add the length specifier then it will read exactly that many characters. I would guess by your code that isn't the case.(just for personal clarification)
Sounds like you're using Visual Studio in debug mode: 0xcccccccc is uninitialized stack memory (that is, the contents of your variable floors) which the program attempted to use as an address (location 0xcccccccc). The reason is the same as the compiler diagnostic I quoted: fscanf expects a pointer to int, not an int, to match the %i conversion specifier.
When using any of the scanf functions, always make use of their return value so you can see how well it worked. If you don't, it is a recipe for the use of non-initialised data. A particular problem is if only some of them a read in because you had the format string wrong. Using a switch is a good way to handle this.
Same with opening files - you have to check to see if it worked.
When using fprintf, I like to use sprintf first, see how well that went, then use fprintf with the string. Check to see whether the fprintf call worked as well.