有一个项目,我应该要求用户输入一个文件名,然后接受该文件并创建一个结构数组。我完全迷路了!这是我到目前为止所拥有的
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
string filename;
ifstream inFile;
struct ftballPlayer
{
int NO;
string first;
string last;
char POS;
char clas;
int height;
char ds;
int iheight;
string hometown;
};
int counter=0;
const int MAX_PLAYER=50;
void printList(const ftballPlayer list[], int listSize);
void printOne ( ftballPlayer two);
void getData(ifstream& inFile, ftballPlayer list[], int& listSize);
int main ()
{
ftballPlayer list[MAX_PLAYER] ;
cout << "Enter the name of the input file: " ;
cin >> filename;
inFile.open(filename.c_str () );
if (!inFile)
{
cout<<"Cannot Open Input File."<<endl;
cout<< "Program Terminates!"<<endl;
return 1;
}
inFile.ignore (200,'\n');
getData (inFile, list, counter);
for ( counter = 0;counter < 50;counter++)
{
printOne (list[ counter] ) ;
cout <<endl;
}
return 0;
}
void getData(ifstream& inFile, ftballPlayer list[], int& listSize)
{
ftballPlayer item ;
listSize = 0;
inFile >> item.NO >> item.first >> item.last
>> item.POS >> item.clas >> item.height
>> item.ds >> item.iheight >> item.hometown;
while (inFile )
{
list [listSize ] = item ;
listSize++;
inFile >> item.NO >> item.first >> item.last
>> item.POS >> item.clas >> item.height
>> item.ds >> item.iheight >> item.hometown;
}
inFile.close () ;
}
void printList(const ftballPlayer list[], int listSize)
{
int looper;
for ( looper = 0; looper < listSize ; looper++)
{
printOne ( list [looper] );
cout << endl ;
}
}
void printOne ( ftballPlayer one)
{
cout << fixed << showpoint << setprecision (2);
cout << "NO " << one.NO;
cout << setw(5) << left << " Name: " << one.first << " " << one.last;
cout << " POS " << one.POS << setw(5);
cout << "Class "<<one.clas<<setw (5);
cout << "Height "<<one.height<<" "<<one.ds<<" "<<one.iheight<<setw(5);
cout << "Hometown " << one.hometown << endl;
}谁能告诉我我是不是在正确的轨道上?打印出来的我得到的甚至不是接近文本文件,就是这样。
没有名字,POS,班级高度,体重,家乡/高中/最后一所大学 60乔希·曼恩·索索6-4 300弗吉尼亚海滩,弗吉尼亚州/海洋湖泊 64 Ricky Segers K/P FR 5-11 185格伦艾伦,弗吉尼亚州/亨里科 70 Brandon Carr OL RS_SR 6-2 305切萨皮克,弗吉尼亚州/西部分校/福克斯联合军事学院 53卡尔弗特库克LB FR 6-0 250诺福克,弗吉尼亚州/布克T.华盛顿 51 Michael Colbert DE RS_SR 6-1230 Fayetteville,N.C./E.E. Smith 22 T.J. Cowart CB RS_JR 5-9 190弗吉尼亚海滩,弗吉尼亚州/海洋湖泊 1 Jakwail Bailey WR . SO 5-11 185 Haddonfield,N.J./Paul VI 25 Andre Simmons S JR 6-0 205 Lorton,弗吉尼亚州/南县/范德比尔特 34 Johnel Anderson RB FR 5-8 180 Sicklerville,N.J./Paul VI
这是用户可以输入的三种信息之一,但它们都具有相同的信息类型。我查阅了我的课本,并在网上搜索了几个小时,当用户输入文件而不是仅仅从文件开始时,我找不到任何关于这样做的信息。任何帮助或指导都将不胜感激。
发布于 2012-11-13 23:11:49
我马上就看到了一些不对的事情。
struct ftballPlayer
{
int NO;
string first;
string last;
char POS; // Should be multiple characters
char clas; // Should be multiple characters
int height;
char ds;
int iheight;
string hometown;
};我怀疑,如果你得到合适的大小,你的POS/ clas,它会更好的工作。为什么不给他们点条件呢?
另外,读最后一段也有一些问题。看上去你必须找出不同的部分,但我没看到你这么做。
总的来说,如果您可以更改输入的格式,那么阅读这篇文章就会更加清晰,但我怀疑您无法做到这一点。逗号分隔的值非常容易阅读,任何其他分隔符也是如此。
https://stackoverflow.com/questions/13370459
复制相似问题