Hello,
I'm using ifstream and the >> operator to read data from a TXT. The goal is to read in 15 chars (together, NOT separated by spaces) into a "char temp_buffer[16]". After reading it in, I immediately set temp_buffer's index [15] to 0, to insert a null terminator, so that it can be safely cout'ed without continuing to cout garbage.
-
Secondary question: Setting aforementioned buffer's index [15] to 0 is necessary, correct? Because, if for example, I make a char Hey[3] in main, where [0] is 'H', [1] is 'e', and [2] is 'y', and if I "cout << Hey;", it will cout garbage afterward, like "Hey*#&$**||||||||||@*#$*@||||:2".
-
So, my question about the reading from the TXT file into a buffer is that -- it works -- but only if the characters being read in are 15 or less. If there are 16 or more letters, I get a "stack around temp_buffer corrupted", since it's trying to shove more than it can hold into the buffer. That's the idea of my buffer though: I want it to only STORE as much as it can hold!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
void LoadActor(void)
{
ifstream LOADFILE;
LOADFILE.open("ACTOR1.txt", ios::in);
if(LOADFILE.is_open() == true)
{
// Some temporary variables to attempt loading into
char temp_actor_name[16];
char temp_actor_type[16];
temp_actor_name[0] = 0;
temp_actor_type[0] = 0;
int temp_tile_sheet_id = -1;
int temp_tile_value_id = -1;
LOADFILE >> temp_actor_name;//PROBLEM IS HERE (I assume)
LOADFILE >> temp_actor_type;//PROBLEM IS HERE (I assume)
LOADFILE >> temp_tile_sheet_id;
LOADFILE >> temp_tile_value_id;
LOADFILE.close();
// Set last (16th) character to null
temp_actor_name[15] = 0;
temp_actor_type[15] = 0;
}
}
|
In my TXT file:
(example of TXT file that DOES load)
(example of TXT file that CORRUPTS stack)
(because the first field is greater than or equal to 16 chars long)
1 2 3 4
|
Electro_Magnetic
Eggs
13
9
|
Of course, in this code, nothing is happening when data is read into the buffers, but first I want to understand how to avoid corrupting the stack around the buffer.
Thank you for any advice!