2012-03-15 45 views
0

只需要一般的项目帮助。 基本上我需要为8名球员做到这一点。这些数据来自一个我应该打入的文件。前5场比赛的前5个数字,下一个篮板数据,然后是块数。我假设我需要调用一个循环来读取名字,姓氏,积分,篮板和块,处理该信息,然后输出信息。任何提示/建议?从文本文件通过文件排序/返回信息

例如:从什么我应该

Thomas Robinson 17 28 10 16 10 11 12 13 8 9 1 1 1 0 1 

前把这些信息返回

  Game Log 
----------------------------------------------------------------------------- 

Player Name : Thomas Robinson 
----------------------------------------------------------------------------- 
Game #  Points  Rebounds  Blocks 
----------------------------------------------------------------------------- 
    1 17 11 1 
    2 28 12 1 
    3 10 13 1 
    4 16 8 0 
    5 10 9 1 
----------------------------------------------------------------------------- 
+2

欢迎来到Stack Overflow!你试过什么了?什么给你带来了问题? – 2012-03-15 01:30:38

+0

老师不会让我们调用预定义的函数,所以我们必须创建自己的函数。使用数组和循环。现在我正在努力获得一个数组,以加载玩家的名字并将统计数据插入表中。 – user1270476 2012-03-15 01:38:19

回答

0

我认为这是家庭作业,但因为我不知道是哪个功能可以使用,哪些功能不能,我的答案可能不能满足要求。

第一次看,我有三个想法。使用ifstream::get()

ifstream in_file; 
in_file.open("your_file_name.txt"); 
char ch; 
string str = ""; 
while(in_file.get() != '\n') 
{ 
    str = ""; 
    while((ch = in_file.get()) != ' ') 
    { 
    // add ch to str. 
    str += string(&ch, 1); 
    } 
    // push str into an array, vector, stack, etc. 
    /*...*/ 
} 
in_file.close(); 

2)读行成一个string,然后用split功能

1),你可以找到如何到处实现split功能。

3)使用ifstream::getline()函数,它提供了一个delemiter参数。

,你可以找到ifstream::get()使用和ifstream::getline()herehere

我在1提供的代码)可能不是一个很好的做法,你应该检查“EOF”流错误,in_file.open()的异常等。

顺便说一句,我第一次写的代码是一个错误代码,您不能使用str += string(ch),您应该写str += string(&ch, 1)str += string(1, ch)str += ch你可以找到string的构造here。对不起,再次出现错误代码。

+0

'str + = string(ch);'真的吗?此外,您不会正确处理意外的EOF(或其他流错误)。 – Josh 2012-03-15 02:13:06

+0

感谢帮助,即时调查现在执行此权利。我会让你知道它很快会如何。 – user1270476 2012-03-15 02:17:25

+0

@Josh嗯......代码没有正确验证,只是提供了解决问题的方法。 – shengy 2012-03-15 02:28:35

0

如果所有内容都由空格和换行符分隔,则可以使用“>>”运算符很好地解析文件。 “>>”运算符是如何工作的。所以,是的,你需要一个循环。基本上你想循环工作是这样的:

(我从来不知道你可以在Comp Sci 1中做到这一点。它会救了我很多麻烦......我曾经做过类似其他答案的事情这样做。)

(我也假设你知道如何打开一个txt文件作为ifstream的。如果不是看到http://www.cplusplus.com/reference/iostream/ifstream/open/

int temp; 
int n = 0; 
int x = 1; 

while(textfile >> temp) // Each time through the loop, this will make temp 
         // the next value in the file. It will stop when 
         // there's nothing more to read. 
{ 
    /* Now it's going to go from left to right through the file, so you 
     need some logic to put it in the right place. you know that every 
     five numbers start a new column, so:*/ 

    array[x][n] = temp; //Start x at 1 because you're skipping the first column 
    n++; 
    if (n == 5) { 
     n = 0; 
     x++; //Every five values, move on to the next column 
    } 

现在你的阵列将拥有的东西需要的地方是。只需按计划输出。