Reputation: 449
I am reading an input file line by line by using ifstream and getline (say in string line
). And I have to output string line
to a file by removing first character of it. What I am doing is erase
ing first character of line and outputting it using ofstream. Is there any better method to do it (means relatively faster one) ? I have millions of strings. (note that this is not true for all the lines, only for first line of every 10 line).
Upvotes: 0
Views: 1104
Reputation: 55415
I'd try the simplest approach first and see if it's fast enough:
if (!mystring.empty())
std::copy( mystring.begin() + 1, mystring.end(),
std::ostreambuf_iterator<char>(stream_object) );
You'll need <algorithm>
and <iterator>
headers.
Upvotes: 2
Reputation: 409356
You could output the actual string pointer plus one:
outputStream << (line.c_str() + 1);
However, you should better check that the string is not empty first, or you might end up accessing an illegal pointer.
If you want to output a substring there's the std::string::substr
function. Or use the std::ostream::write
function combined with the pointer arithmetic outlined above:
outputStream.write(line.c_str() + 1, 9); /* 1st to 10th character */
For the above, you have to make sure the length of the string is at least ten characters.
Note: I personally would not use "hacks" as the ones outlined in this answer, unless in extreme situations. The substring function is there for a reason, and is the one I would recommend using.
Upvotes: 1
Reputation: 5054
Maybe the fastest way to write whole string without 1st char is from @JoachimPileborg answer.
But if you want to write 10 chars from 1st to 10th, then the fastest way is to use fwrite
function instead of fstream
.
fwrite( line.c_str() + 1, 1, 10, file );
Pay an attention, that you should use it very accurate. You should be assured, that line has more then 10 chars.
Upvotes: 0
Reputation: 3221
I assume you are using std::string...
std::string str; // contains the line
str.substr (1, str.length() - 1); // gives you what you need
Best, Akos
Upvotes: 0