C++ - 读取文件,直到使用>>运算符到达行尾

C++ - Read file until reaching end of line with >> operators

本文关键字:gt 运算符 读取 文件 C++      更新时间:2023-10-16

我环顾四周,仍然没有找到如何做到这一点,所以,请耐心等待。

假设我必须读取一个包含不同类型数据的 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;
}

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

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

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

// assuming your file is open
string line;
while(!file.eof())
{
   getline(file,line);
  // then do what you need to do
}

要跳过任何字符,您应该在到达while(file.peek() != 'n')之前尝试调用这样的函数

istream& eatwhites(istream& stream)
{
    const string ignore=" tr"; //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
}

在您和其他朋友的帮助下,我最终将代码更改为使用 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;
    }

谢谢你的时间!