I wanted to write a simple function that will take a file name as an argument and then return a constant char pointer that contains the characters in the text file.
#include <fstream> #include <vector> #include <iostream> #include "text.h" //function to get the size of a file unsigned int Get_Size(const char * FileName){ std::ifstream filesize(FileName, std::ios::in|std::ios::ate); unsigned int SIZE = filesize.tellg(); filesize.close(); return SIZE; } //Takes a file name then turns it into a c-style character array const char * Get_Text(const char * FileName){ //get size of the file unsigned int SIZE = Get_Size(FileName); std::ifstream file(FileName, std::ios::in); //I used a vector here so I could initialize it with a variable std::vector<char> text(SIZE); //here is where I loop through the file and get each character //and then put it into the corresponding spot in the vector std::streampos pos; for(int i = 0; i<SIZE; i++){ pos=i; file.seekg(pos); text[i] = file.get(); } //I manually added the terminating Null character text.push_back('\0'); //I set the pointer equal to the address of the first element in the vector const char * finalText = &text[0]; file.close(); //this works std::cout<<finalText<<std::endl; return finalText; }; int main(){ //this does not work std::cout<<Get_Text("Text.txt")<<std::endl; return 0; } When I print the the text with the *char pointer inside of my function it works. But when the pointer is passed outside of the function and I try to use it, the output is a white box for each character in the console. I have tried a bunch of different things and nothing gets it to work. I don't understand why it works inside of the function but it doesn't work outside.
c? Which version of the C standard library suppliesstd::vector?new string[size]) and returning that buffer. Even better, just usestd::strng,std::getlineandstd::string::operator+=.