The intent of the following code is to read the first 2 characters from each
line until EOF is reached. It does this correctly on the first line but
stores an empty string for all subsequent lines. Of course I an accomplish
this task in other ways but I was wondering why this approach didn't work.
Thanks
char buf[512];
while (!cin.getline(buf, 3).eof())
{
cout << buf << '\n';
cin.ignore(100, '\n');
}
This is why I don't like the iostream classes. After the initial
getline, the state has been set with failbit. It must be reset or
something. I hate these classes and never use them. :)
Try like this
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
while (getline(cin, s) && !s.empty())
{
cout.write(s.c_str(), 2) << "\n";
}
return 0;
}
--
David Wilkinson
Visual C++ MVP
"David Wilkinson" wrote:
> .
>
David,
Thanks for your suggestion. However, my issue here is not how to accomplish
the task, which I can do, but rather, what precisely is wrong with the
approach I took in the code sample I provided.
Ray
This is a well-known and standard behaviour and
Stephan T. Lavavej explains it extensively here:
ID:351636 "STL: ifstream::getline() doesn't set eof flag"
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=351636
Best regards,
--
Mateusz Loskot, http://mateusz.loskot.net
Charter Member of OSGeo, http://osgeo.org
This is a well-known and standard behaviour and
Scot told you the answer. Look at the documentation for getline. If the
"get" terminates because it encountered the character limit before it found
the end-of-line character, it sets "failbit" on the stream.
Call cin.clear(); to clear the failbit condition.
--
Tim Roberts, ti...@probo.com
Providenza & Boekelheide, Inc.