[英]Reading file in C++ through ifstream object
I have a program written for reading files using ifstream object. 我有一个程序编写用于使用ifstream对象读取文件。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct FPlayerInfo
{
string name;
string pos;
int numTouchDowns;
int numCatches;
int numPassingYards;
int numReceivingYards;
int numRushingYards;
};
void loadInfo(FPlayerInfo info[10], string filename)
{
int i=0;
ifstream ifs(filename.c_str() , ios::in);
if (ifs.good() && ifs.is_open())
{
string line;
while (getline(ifs, line))
{
ifs >> info[i].name >> info[i].pos >> info[i].numTouchDowns >> info[i].numCatches >> info[i].numPassingYards
>> info[i].numReceivingYards >> info[i].numRushingYards;
cout << info[i].name << endl;
i++;
}
ifs.close();
}
}
int main()
{
FPlayerInfo info[10];
loadInfo(info , "Footballdata.txt");
return 0;
}
The Footballdata.txt contains the following data: Footballdata.txt包含以下数据:
Bill Quarter_Back 70 0 8754 0 573
Jackson Receiver 55 87 50 5490 574
Grahm Running_Back 45 30 0 50 2800
McCoy Full_Back 25 10 0 25 3762
Daryl Quarter_Back 50 2 7560 0 450
Santiago Left_Tackle 5 0 0 0 0
Hanks Receiver 35 37 0 3590 876
Johnson Running_Back 25 80 0 100 4000
Miller Receiver 110 250 150 7867 2100
Ruth Quarter_Back 85 0 12901 0 3249
After execution of the above program, I expect all the names to be returned in the output. 执行完上述程序后,我希望所有名称都将在输出中返回。 But What I observed is that the first name is missing in the actual output and last line I am getting blank.
但是我观察到的是实际输出中缺少名字,而最后一行却变得空白。 Can anyone please tell me where I am making mistake while reading the file ?
有人可以告诉我在读取文件时我在哪里出错吗?
Thanks in advance. 提前致谢。
Actual Output: 实际输出:
Jackson
Grahm
McCoy
Daryl
Santiago
Hanks
Johnson
Miller
Ruth
getline
reads a line from the input and then ifs >> info[i].name >> ..
reads additional info thus skipping what you have read using getline
. getline
从输入中读取一行,然后ifs >> info[i].name >> ..
读取其他信息,从而跳过使用getline
阅读的内容。
Simply change: 只需更改:
string line;
while (getline(ifs, line))
{
ifs >> info[i].name >> info[i].pos >> info[i].numTouchDowns >> info[i].numCatches >> info[i].numPassingYards
>> info[i].numReceivingYards >> info[i].numRushingYards;
[..]
}
Into: 成:
while (true)
{
ifs >> info[i].name >> info[i].pos >> info[i].numTouchDowns >> info[i].numCatches >> info[i].numPassingYards
>> info[i].numReceivingYards >> info[i].numRushingYards;
if (!ifs) break;
[..]
}
An better implementation (splitted to avoid littering the actual issue), is using a temp object and moving it once we realized the read was successful: 更好的实现 (为了避免乱扔实际问题而进行拆分)是使用临时对象,并在我们成功读取后将其移动:
while (true)
{
FPlayerInfo temp;
ifs >> temp.name >> temp.pos >> temp.numTouchDowns >> temp.numCatches >> temp.numPassingYards
>> temp.numReceivingYards >> temp.numRushingYards;
if (!ifs) break;
info[i] = std::move(temp);
[..]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.