我在打印文本文件时遇到问题,这就是我要打印的内容
Michael 33 76 81
Brenda 44 79 90
Alex 79 88 70
Brian 82 93 50
Kevin 77 73 80
这是我的程序
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
struct STUDENT
{
string name;
int Exam1;
int Exam2;
int Exam3;
};
STUDENT S[5];
int main()
{
ifstream f;
f.open("data.txt");
for(int i=0;i<5;++i)
{
f.getline(S[i].name,5,'\n');
f>>S[i].Exam1>>S[i].Exam2>>S[i].Exam3;
cout<<S[i].Exam1<<S[i].Exam2<<S[i].Exam3<<endl;
}
f.close();
system("pause");
return 0;
}
当我运行程序时,它只打印一行零
答案 0 :(得分:0)
您需要对阅读名称进行一些小改动 - 您需要记住打印它以及空格!
for(int i=0;i<5;++i)
{
getline(f, S[i].name, ' '); // <<<< only read up to the space, not the end of line
f>>S[i].Exam1>>S[i].Exam2>>S[i].Exam3;
cout<<S[i].name<<" "<<S[i].Exam1<<" "<<S[i].Exam2<<" "<<S[i].Exam3<<endl;
}
我的整个计划:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
struct STUDENT
{
string name;
int Exam1;
int Exam2;
int Exam3;
};
STUDENT S[5];
int main()
{
ifstream f;
string buf;
f.open("data.txt");
for(int i=0;i<5;++i)
{
getline(f, S[i].name, ' ');
f>>S[i].Exam1>>S[i].Exam2>>S[i].Exam3;
cout<<S[i].name<<" "<<S[i].Exam1<<" "<<S[i].Exam2<<" "<<S[i].Exam3<<endl;
}
f.close();
system("pause");
return 0;
}
输入文件data.txt
:
Michael 33 76 81
Brenda 44 79 90
Alex 79 88 70
Brian 82 93 50
Kevin 77 73 80
使用g++
编译,会产生输出
Michael 33 76 81
Brenda 44 79 90
Alex 79 88 70
Brian 82 93 50
Kevin 77 73 80
sh: pause: command not found
我不明白你为什么不这样做,除非你没有正确复制我的代码样本......