C++ - 读取文件,直到使用>>运算符到达行尾
C++ - Read file until reaching end of line with >> operators
我环顾四周,仍然没有找到如何做到这一点,所以,请耐心等待。
假设我必须读取一个包含不同类型数据的 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;
}
谢谢你的时间!
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 是否需要使用 - &gt;运算符在C 中调用成员函数时