Re: Return Array Function
Why not try something like this:
Code:
int LoadText(const std::string& filename, std::string& buffer)
{
std::ifstream fs(filename);
if (!fs) return -1;
std::copy( std::istreambuf_iterator<char>(fs),
std::istreambuf_iterator<char>(),
std::back_inserter(buffer) );
return 0;
}
std::string filetext;
if ( LoadText("somefile.txt", filetext) )
{
std::cout << filetext;
}
else
{
std::cout << "Couldn't open file!";
}
If you really want to access the text by indexing by line number, then maybe something like this:
Code:
int LoadText(const std::string& filename, std::vector<std::string>& buffer)
{
std::ifstream fs(filename);
if (!fs) return -1;
std::string line;
while ( std::getline(fs, line) )
{
buffer.push_back(line);
}
return 0;
}
std::vector<std::string> filetext;
if ( LoadText("somefile.txt", filetext) )
{
std::cout << filetext[0]; //first line
}
else
{
std::cout << "Couldn't open file!";
}
Re: Return Array Function
Thanks a lot for the help :). I realize i may have posted this in the wrong section because i am using Visual C++ and it has given me errors in the past with strings.
I am getting this error:
cannot convert parameter 1 from 'const std::string' to 'const char *'
I tried making it a cont char * and though it will run it crashes immediately on the second example code and does nothing on the first. Anyway you can help me out again? or should i be making a thread in the Visual C++ board?
Re: Return Array Function
There is no implicit conversion from std::string to const char *. Moreover, they are basically incompatible so doing a simple serach-and-replace between the two is an almost 100% certain way to ruin your program.
However, there is a member function of std::string called c_str() which does exactly the conversion you want. You just need to call it explicitly.
EDIT: And note that this is all standard stuff and should apply likewise to any (decent) compiler.
Re: Return Array Function
Yea i was 90% certain it would not work but i gave it a shot. Thank you for the c_str()