我是编程和c ++的新手。我正在进行一项任务,要求我从数据文件中读取数据并将其存储到2D数组中。文本文件中的每一行都采用以下格式(数据类型为int)
XXXX XX XX XX XX ......(依此类推)
四位数字实际上是学生ID,将存储在单独的一维数组中。我做了这个部分,我没有任何问题。现在剩余的2位数字将存储在具有4列和X行的2D数组中,其中X是数据文件中的行数。
我已编写以下代码以尝试读入该文件。它没有给出任何错误并且编译正确但是当我尝试使用cout
打印2D数组时,我什么也得不到。没有。请查看以下代码并尝试帮助我。
我是stackoverflow和编程的新手,所以请原谅我代码格式不正确或不符合传统。
//___CODE____
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
//Global
const int SIZE = 1000;
int const col = 4;
string fileName;
//Function Prototypes
int readId(int id[], int size);
int readScores(int scores[][col], int size);
//Main
int main()
{
int examScores[SIZE][col];
int id[SIZE] = {};
cout<<endl;
readId(id, SIZE);
readScores(examScores, SIZE);
}
//Declarations
int readId(int id[], int size)
{
ifstream inputFile;
int count = 0;
int total = 0; //Size of id [] OR no. of students.
int temp = 0;
//Takes the name of the data file from the user.
//NOTE: The filename should include its extension.
cout<<"Enter the name of the data file (including the extension):";
cin>>fileName;
inputFile.open(fileName.c_str());
if(inputFile.is_open())
{
while(inputFile >> temp)
{
if(count % 5 == 0)
{
id[total] = temp;
total++;
}
++count;
}
}
else
cout<<"Data file not found!"<<endl; // If this is executed make sure the data file
//is located in the same directory as this program.
//To print the content of array. Check.
for(int i=0; i < total; i++)
cout<<id[i]<<endl;
return total;
}
int readScores(int scores[][col], int size)
{
ifstream inputFile;
int count = 0;
int c = 0; //Counter for column.
int total = 0; //No. of students.
int temp = 0;
inputFile.open(fileName.c_str());
if(inputFile.is_open())
{
while(inputFile >> temp)
{
if(count % 5 != 0)
{
if (c < col)
{
scores[total][c] = temp;
}
else
total++;
c = 0;
scores[total][c] = temp;
}
++count;
c++;
}
}
else
cout<<"Data file not found!"<<endl; // If this is executed make sure the data file
//is located in the same directory as this program.
//To print the contents of 2D array. Check.
for (int r = 0; r < total; r++)
{
for (c = 0; c < col; c++)
{
cout<<setw(8)<<scores[r][col];
}
cout<<endl;
}
return total;
}
答案 0 :(得分:0)
你的其他声明是错误的,有一些括号丢失(现在你总是把c重置为零)