How to detect the end of a line from a file stream in C++

≡放荡痞女 提交于 2019-12-12 02:48:35

问题


I have csv file input where I read in multiple lines which contain multiple fields related to that line. How do I write a loop which reads a line of text from the csv file, then keeps looping until it reaches the end of that line. This while loop would be nested in an !infile.eof while loop. Here is what I has so far but doesn't work exactly.

while (getline(infile, currentline))
{

    getline(infile, ID, ',');
    getline(infile, Name, ';');

Person p = new Person(ID, Name);

}

A line in the csv file looks like this: 111, james; 222, lynda; 333, luke;

Each line represents a classroom so there would be multiple lines.


回答1:


Try this:

while (getline(infile, currentline))
{
    std::istringstream line{currentline};
    if(getline(line, ID, ',') && getline(line, Name, ';'))
        Person p = new Person(ID, Name);
}

This while loop would be nested in an !infile.eof while loop.

As a side note, never iterate while( !infile.eof() ) - this is pretty much guaranteed to be a bug. An input stream has multiple failure conditions (eof, failed read etc).

You should simply cast the stream to a boolean value for checking.




回答2:


The question's a mess, but I think this is what you want:

while (std::getline(infile, currentline))
{
    std::istringstream iss(currentline);
    if (getline(iss, ID, ',') && 
        getline(iss, Name, ';') &&
        ...)
    {
        Person p = new Person(ID, Name);
        ...
    }
    else
        ...bad person ;-P...
}



回答3:


Your while loop seems to already extract a line from the "infile" and stores it in "currentline". Inside the loop you should make a stream out of this string, and use the getlines for "ID" and "Name" on the "currentline"-stream. Otherwise, as it is now, I think you lose every other line.



来源:https://stackoverflow.com/questions/23754341/how-to-detect-the-end-of-a-line-from-a-file-stream-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!