Hello everyone. I am trying to copy data from a file stream into a char*. I know there are ways to do it with std::string and getline, but I have an assignment where I have to have a class that will take a char* into one of its constructors (which will represent the data in the file), hence forcing me to not use strings.

And so, my question really is how do I get file stream data and put it into a char*? I've attempted to do this with the code below, but the program keeps crashing. What is the best way to go about doing this? I know strings are recommended.. but I really have no choice in this case. I've looked at several text books, online tutorials, google, but to no avail, everyone uses strings.

#include <iostream>
#include <fstream>
#include <cstring>

int main()
   std::ifstream dataFile("strings.txt"); // strings.txt contains "this is my string" or w/e

   char* str;
      dataFile >> str;

   std::cout << str;

   return 0;

Recommended Answers

All 5 Replies

First you didn't allocate any memory for the str character pointer....

I made str dynamic now.

char* str = new char[];

.. but it now gives me only the last word in the text file.

Here is my new version, but now I get 2 random letters on the end.

char* str = new char[];

int i = 0;
	dataFile >> str[i];

Edit: I don't really care about spaces being gone as long as I don't have extra characters I don't need since later on I will only be needing to work with the 26 letters in the alphabet.

Your allocating memory but you haven't requested a size.


char *str = new char[sizeof(char) * 100];

To allocate a memory chunk equal to 100 bytes.

Okay I fixed my code and it works now. Thank-you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.