On 12/3/2014 2:34 PM, Victor Bazarov wrote:
> On 12/3/2014 3:26 PM, Christopher Pisz wrote:
>> I need to replace any occurance of "\r\n" occurring in an istream with
>> just "\n".
>>
>> I could so this by copying the stream contents to a string, then
>> replacing the occurances within the string, and creating another stream
>> object from that string.
>>
>> Is there a more efficient way?
>
> First you need to ask yourself, what is inefficient about it?
> Second, why bother with creating another stream when you can simply
> incorporate that action into your stream parser?
>
> V
Seems very inefficient to be copying string to stream and back again.
Here is a compilable example of what I have:
// Standard Includes
#include <iostream>
#include <sstream>
#include <vector>
// Existing function to replace occurances of a string within a string
std::string ReplaceAllOccurrences(const std::string & original, const
std::string & search, const std::string & replacement)
{
std::string temp = original;
size_t position = 0;
while((position = temp.find(search, position)) != std::string::npos)
{
temp.replace(position, search.length(), replacement);
position += replacement.length();
}
return temp;
}
// Function I am working on
void Test(std::istream & stream)
{
// Verify the stream is good
if(!stream)
{
// Error - stream was given in an error state
throw std::exception("Stream to be parsed was given with an
error state set");
}
// Replace all occurances of "\r\n" with "\n" so the newline can be
handled the same way
// TODO - This can't be the most efficient way
stream.seekg (0, stream.end);
const unsigned length = stream.tellg();
stream.seekg (0, stream.beg);
std::string temp('\0', length);
temp = ReplaceAllOccurrences(temp, "\r\n", "\n");
std::istringstream formattedStream(temp);
// Snip the actual work
}
// Test
int main()
{
std::istringstream testData("Hello\r\nI am a Windows
string\r\nBecause I like carriage returns\r\n");
Test(testData);
}