On 3/5/2015 3:35 PM, Ben Bacarisse wrote:
Christopher Pisz <nospam@notanaddress.com> writes:
I know there exists a way to copy a filestream into a string in one
line, using iterators, because I've seen it before on this newsgroup.
I looked up the documentation, but can't seem to get the syntax right.
My attempt:
std::ifstream("test.txt");
if( !file )
{
// Error
}
std::string textToParse;
textToParse.assign(std::istreambuf_iterator<char>(file),
std::istream_iterator<char>());
Did you mean something like this:
file >> std::noskipws;
std::copy(std::istream_iterator<char>(file),
std::istream_iterator<char>(),
std::inserter(textToParse, textToParse.begin()));
?
<snip>
Indeed!
Full listing (make your own timer and exception classes):
// Shared Includes
#include "Exception.h"
#include "PerformanceTimer.h"
// Standard Includes
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
//--------------------------------------------------------------------------------------------------
void Method1()
{
std::ifstream file("test.txt");
if( !file )
{
// Error
throw Shared::Exception(__FILE__, __LINE__, "Cannot open test
file");
}
std::string textToParse;
file >> std::noskipws;
std::copy(std::istream_iterator<char>(file),
std::istream_iterator<char>(),
std::inserter(textToParse, textToParse.begin()));
file.close();
}
//--------------------------------------------------------------------------------------------------
void Method2()
{
std::ifstream file("test.txt");
if( !file )
{
// Error
throw Shared::Exception(__FILE__, __LINE__, "Cannot open test
file");
}
std::stringstream textToParse;
textToParse << file.rdbuf();
file.close();
}
//--------------------------------------------------------------------------------------------------
int main()
{
Shared::PerformanceTimer timer;
Method1();
std::cout << "Method 1 :" << timer.Stop() << std::endl;
timer.Start();
Method2();
std::cout << "Method 2 :" << timer.Stop() << std::endl;
}
Output:
Method 1 :0.283209
Method 2 :0.0216563
That's quite a difference! What's going on under the hood with the
iterator method?
methods...