读取文本文件并在 C++ 中显示数据
我想读取一个文本文件并显示数据。问题是 while 循环没有结束并且不显示任何内容。怎么了?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
/* text file example:
john
3453
23
james
87
1
mike
9876
34
*/
struct entry
{
// Passengers data
std::string name;
int weight; // kg
std::string group_code;
};
entry read_passenger(std::ifstream &stream_in)
{
entry passenger;
if (stream_in)
{
std::getline(stream_in, passenger.name);
stream_in >> passenger.weight;
std::getline(stream_in, passenger.group_code);
stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return passenger;
}
int main(void)
{
std::ifstream stream_in("data.txt");
std::vector<entry> v; // Contains the passengers data
const int limit_total_weight = 10000; // kg
int total_weight = 0; // kg
entry current;
if (stream_in)
{
std::cout << "open file" << std::endl;
while (!stream_in.eof()) // Loop has no end
{
std::cout << current.name << std::endl; // Nothing will be displayed
}
return 0;
}
else
{
std::cout << "cannot open file" << std::endl;
}
}
I want to read a text file and display the data. The problem is that the while loop has no end and does not display anything. What's wrong?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
/* text file example:
john
3453
23
james
87
1
mike
9876
34
*/
struct entry
{
// Passengers data
std::string name;
int weight; // kg
std::string group_code;
};
entry read_passenger(std::ifstream &stream_in)
{
entry passenger;
if (stream_in)
{
std::getline(stream_in, passenger.name);
stream_in >> passenger.weight;
std::getline(stream_in, passenger.group_code);
stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return passenger;
}
int main(void)
{
std::ifstream stream_in("data.txt");
std::vector<entry> v; // Contains the passengers data
const int limit_total_weight = 10000; // kg
int total_weight = 0; // kg
entry current;
if (stream_in)
{
std::cout << "open file" << std::endl;
while (!stream_in.eof()) // Loop has no end
{
std::cout << current.name << std::endl; // Nothing will be displayed
}
return 0;
}
else
{
std::cout << "cannot open file" << std::endl;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来您忘记调用
read_passenger
,因此您的循环不断地一次又一次地打印current.name
的默认(空)值。 (不过,您应该得到很多很多换行符,这并不完全是“不显示任何内容”)。It seems you forgot to ever call
read_passenger
, so your loop keeps printing the default (empty) value ofcurrent.name
again and again. (You should get lots and lots of newlines, though, which isn't exactly "does not display anything').