使用文件和结构读取数据并输出数据
Using files and structs to read data and output it
Mike 85 83 77 91 76 CSC
马克 80 90 95 93 48 CSC
安德森 78 81 11 90 73 巴士
布莱尔 92 83 30 69 87 欧洲经委会
苏茜 23 83 30 69 87 ARC
卡洛斯 46 76 90 54 38 大众通信
所以我有这个文件,我需要读取它的数据并使用结构体通过控制台输出它,我已经设法阅读了迈克的名字和他的分数和教师,但这就是我卡住的地方,我怎么能继续阅读?
这是我的代码
struct student {
string name;
int scores[5];
string faculty;
};
void main() {
student x;
ifstream myfile("D:\Test\MIUCS.txt");
myfile >> x.name;
for (int j = 0; j < 5; j++) {
myfile >> x.scores[j];
}
myfile >> x.faculty;
cout << x.name << " ";
for (int k = 0; k < 5; k++) {
cout << x.scores[k] << " ";
}
cout << x.faculty << endl;
}
提示:我的教授说要使用我无法真正实现的类型学生(结构(数组,任何帮助将不胜感激,谢谢。
如何继续阅读?
将代码包装在while
循环中读取/写入。继续阅读和写作,直到没有可读的东西。
while ( myfile >> x.name )
{
for (int j = 0; j < 5; j++)
{
myfile >> x.scores[j];
}
myfile >> x.faculty;
// If there was any error in reading from myfile, break out of the loop.
if ( !myfile )
{
break;
}
cout << x.name << " ";
for (int k = 0; k < 5; k++)
{
cout << x.scores[k] << " ";
}
cout << x.faculty << endl;
}
您可以通过将用于读取和写入的代码移动到它们自己的函数来简化循环。
while ( myfile >> x )
std::cout << x << std::endl;
为了使用上述功能,您需要重载operator>>
函数和operator<<
函数,如下所示:
std::istream& operator>>(std::istream& in, student& s);
std::ostream& operator<<(std::ostream& out, student const& s);
我会把它留给你进行下一步。
相关文章:
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 使用 python 或 c ++ 中的 sql 根据输入数据输出输出示例
- 尝试从 txt 文件中读取两条数据并输出它们 [C++]
- 将多个效果与 libSox 链接并读取输出数据的正确方法
- 如何将函数的输出数据存储在文本文件中
- 如何从amd gpus的显示输出中获取图像数据
- 自定义堆栈上 std::string 数据的输出
- 如何从文本文件输出数据?(学生成绩单计划)
- 为什么我的数据/输出文件为空?
- C++:如何将数据输出到多个.dat文件
- C++:将存储在List容器中的数据输出到文本文件中
- .wav C++数据输出不正确
- C++:模拟餐饮公司计费程序-无法将错误数据输出到错误文件
- 使用iomanip将数据输出格式化为具有Qt的文本文件
- matPutVariable:尝试将数据输出到mat文件时出错(matrix::serialize::WrongSize
- 如何使用类似于gcc-xml的clang生成元数据输出
- 如何使用Python从UART Beaglebone获取数据输出
- GP635T gps传感器的数据输出
- 如何在Windows控制台中将数据输出到自定义流(3>4>等)?
- 流数据输出问题