Skip to main content
GameDev.net gamedev.net
🔒 Locked

C++ dynamic array problem

Started by induster Apr 5, 2008 at 9:26 PM 3 replies 1k views
Original Post
induster
induster
I hope someone can help with this.

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

class TestChecker
{
public:
	TestChecker();
private:
	ifstream getFile;
	char *answerKey;
};

TestChecker::TestChecker()
{
	getFile.open("test_results.txt");
	if( getFile.is_open() )
	{
		getFile >> (answerKey = new char);
		cout << answerKey << endl;
	}
	getFile.close();
}



This copies the txt file just fine as long as there are 8 letters or less. Any more than 8 causes "the memory could not be read" windows error. is there a better technique to filling a dynamic char array? Thanks to anyone that can help here.
Driv3MeFar
Driv3MeFar
Quote:

answerKey = new char;


This allocates enough room for a single character. By reading in more than one character, you're corrupting memory. The real answer, in C++, is to use a std::string:

std::string answerKey;getFile >> answerKey;
RDragon1
RDragon1
Whatever you're using to learn C++ that taught you to write this code is complete garbage.

If you want to read an entire file into a vector:

  ifstream f("file.txt");  vector<char> vec( (istream_iterator<char>(f)), istream_iterator<char>() );
induster
induster
The assignment I'm working on needs me to use a dynamic array to store chars, without using the std::string class. Trust me I wish I could just use strings.

So, I'm going to use vector like you suggest. How can I parse through and seperate each line from the file? Just check my vector for the '/n' ? or do I need some kind of flag character in the file?
kiwibonga
kiwibonga
I don't know if vector is what the professor will be looking for though... Most likely they showed you something specific in class or tutorials and want you to use it... Maybe they're sadistic and want you to code it like it's C...

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.