1

我环顾四周,仍然没有找到如何做到这一点,所以,请多多包涵。

假设我必须读取一个包含不同类型数据的 txt 文件,其中第一个浮点数是一个 id,然后有一些(并不总是相同数量)的其他浮点数代表其他东西......时间,例如, 成对。

所以文件看起来像:

1 0.2 0.3
2.01 3.4 5.6 5.7
3 2.0 4.7
...

经过大量研究,我最终得到了这样的功能:

vector<Thing> loadThings(char* filename){
    vector<Thing> things;
    ifstream file(filename);
    if (file.is_open()){
        while (true){
            float h;
            file >> h; // i need to load the first item in the row for every thing
            while ( file.peek() != '\n'){

                Thing p;
                p.id = h;
                float f1, f2;
                file >> f1 >> f2;
                p.ti = f1;
                p.tf = f2;

                things.push_back(p);

                if (file.eof()) break;
            }
            if (file.eof()) break;
        }
        file.close();
    }
return things;
}

但是带有条件的while循环(file.peek() != '\n')永远不会自行完成,我的意思是......偷看永远不等于'\n'

有人知道为什么吗?>>或者也许是使用运算符读取文件的其他方式?!非常感谢!

4

3 回答 3

6

只是建议另一种方式,为什么不使用

// assuming your file is open
string line;

while(!file.eof())
{
   getline(file,line);

  // then do what you need to do

}
于 2014-12-22T01:17:09.290 回答
2

要跳过任何字符,您应该在到达while(file.peek() != '\n')

istream& eatwhites(istream& stream)
{
    const string ignore=" \t\r"; //list of character to skip
    while(ignore.find(stream.peek())){
        stream.ignore();
    }
    return stream;
}

一个更好的解决方案是将整行读入字符串而不是istringstream用来解析它。

float f;
string line;
std::getline(file, line);
istringstream fin(line)
while(fin>>f){ //loop till end of line
}
于 2014-12-22T01:23:17.533 回答
0

在您和其他朋友的帮助下,我最终将代码更改为使用 getline() 。这是结果,希望对某人有所帮助。

    typedef struct Thing{
        float id;
        float ti;
        float tf;
    };

    vector<Thing> loadThings(char* filename){
        vector<Thing> things;
        ifstream file(filename);
        if (file.is_open()){

            string line;
            while(getline(file, line))
            {
                istringstream iss(line);
                float h;
                iss >> h;
                float f1, f2;
                while (iss >> f1 >> f2)
                {
                    Thing p;
                    p.id = h;
                    p.ti = f1;
                    p.tf = f2;

                    things.push_back(p);
                }
            }
            file.close();
        }
        return things;
    }

感谢您的时间!

于 2014-12-22T01:39:58.983 回答