所以我有一个包含团队和分数的文件,我需要将团队阅读成二维数组,然后将他们的分数记录到一组整数中。
这是我目前的功能代码,如何在团队名称完成后停止阅读,然后将分数存储在一个单独的数组中?
void getData (char array [][COLS], int rows, int scores [])
{
ifstream inFile; //Input file stream object
//Open the file
inFile.open ("scores.txt");
if (!inFile)
{
cout << "Error opening data file!\n";
exit(102);
}
for (int r = 0; r < rows; r++)
{
{
//reads through columns
for (int c = 0; c < COLS; c++)
{
inFile >> array[r][c];
}
}
}
for (int count = 0; count < ROWS; count++)
{
for(int i = 0; i < COLS; i++)
{
cout << array[count][i];
}
}
inFile.close();
}
我的输入文件如下:
Jaquars 23
Colts 23
49ers 13
Lions 13
Titans 7
Redskins 38
Cardinals 14
Buccaneers 36
Seahawks 30
Lions 24
Bears 28
Packers 23
Bears 14
Rams 22
Texans 6
Packers 34
答案 0 :(得分:0)
也许就像这样
for (int r = 0; r < rows; r++)
{
int c = 0;
// keep reading until we hit a space
char ch = inFile.get();
while (ch != ' ')
{
array[r][c] = ch;
c++;
ch = inFile.get();
}
// now read the score
inFile >> scores[r];
// now read until we hit the trailing newline
ch = infile.get();
while (ch != '\n')
{
ch = inFile.get();
}
}
答案 1 :(得分:0)
这应该让你知道如何去做。我没有编译它。但是很好地说明了这一点。 我强烈建议您选择基于地图的解决方案。或使用矢量。
#include <string>
#include <iostream>
#include <fstream>
#include<cstring>
#include<cstdlib>
using namespace std;
int main()
{
ifstream in("DataFile.txt");
string line;
char * pch;
while(getline(in, line))
{
pch = strtok (line.c_str()," ");
while (pch != NULL)
{
//Put some logic here so that in first loop iteration
//first segment(name) gets stored in your char arrays.
//In second iteration, which will return the score, you store that
//in the int array. Do not forget to use atoi() to convert to int before storing.
pch = strtok (NULL," ");
}
}
//There are more elegant ways to split a string in C++
//http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c
return 1;
}
答案 2 :(得分:0)
这就是我的代码
void getData (char array [][COLS], int rows, int scores [])
{
ifstream inFile; //Input file stream object
//Open the file
inFile.open ("scores.txt");
if (!inFile)
{
cout << "Error opening data file!\n";
exit(102);
}
for (int r = 0; r < rows; r++)
{
int c = 0;
char ch;
// keep reading until we hit a space
ch = inFile.get();
while (ch != ' ')
{
array[r][c] = ch;
c++;
ch = inFile.get();
}
// now read the score
inFile >> scores[r];
// now read until we hit the trailing newline
ch = inFile.get();
while (ch != '\n' && ch != EOF)
{
ch = inFile.get();
}
}
for (int count = 0; count < rows; count++)
{
for(int i = 0; i < COLS; i++)
{
cout << array[count][i];
for (int count2 = 0; count2 < rows; count2++)
cout << scores[count2];
}
}
inFile.close();
return;
}