Using peek to make a dynamic array
Hi all!
I'm trying to read a string of characters from a file (terminating at the first space, newline, or tab character), dynamically allocate memory for it, and then copy the contents of the file to the allocated memory.
I keep getting weird output from the following code. For some reason, it allocates the memory for the array fine, but it reports the array size as 4. It only outputs part of the array (first 4 characters), and then when it goes to deallocate the memory, it gives me a heap corruption error! :P I've also reproduced the file's contents at the end of this (really small). Can anyone help figure out what's going wrong here?
Please note the int flag is no longer really used. I used him for debugging earlier.
Thanks!!
-Max
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
char c =0;
char *chararray = NULL;
int flag = 0;
int count = 0;
ifstream myin("mytest.txt");
if (myin.bad())
cout << "Bad file!!";
while (c != '\t' && c != '\n' && c!= ' ')
{
c = myin.peek();
cout << c;
++count;
myin.seekg(count, ios::beg);
flag = myin.tellg();
}
chararray = new char[count];
int sizeofarray = sizeof(chararray);
cout << endl << endl << sizeofarray << endl << sizeof(char) << endl;
myin.seekg(0, ios::beg);
myin.read(chararray, count);
chararray[count] = '\0';
for (int a=0; a < sizeofarray; a++)
cout << chararray[a];
cout << endl << count << endl;
delete chararray;
}
File mytest.txt:
Readmeyoubiotch!! 3.46 34534sdf