【发布时间】:2011-04-12 01:49:00
【问题描述】:
我正在开发一个程序,该程序从格式如下的文件中读取一些数据:
21
285 270 272 126 160 103 1
31
198 180 163 89 94 47 1
32
240 230 208 179 163 104 1
33
15 13 12 14 15 15 0
34
63 61 62 24 23 20 2
我试图将第一个数字读入一个指针数组,将其他 7 个数字读入一个并行的二维指针数组,但由于某种原因,每次我运行我的代码时它都会停止工作。它没有返回错误,但我觉得我的指针使用错误,因为这是我第一次使用指针。数据文件名为“election_data_121.txt”,仅供参考。这是代码。如果有人可以看一下,我将不胜感激:
#include <iostream>
#include <fstream>
using namespace std;
//bool openFileIn(fstream &, char *);
int main()
{
const int PREC_SIZE = 30;
const int CANIDATES = 7;
int *precinct_num[PREC_SIZE];
int *num_votes[PREC_SIZE][CANIDATES];
cout << "Declarations made." << endl;
fstream dataFile; //Make a file handle
cout << "File object made." << endl;
//Open the file and check that it opened correctly
if(!openFileIn(dataFile, "election_data_121.txt"))
{
cout << "File open error!" << endl;
return 0; //Exit the program
}
cout << "File opened." << endl;
//Read the contents of the file into the proper arrays
int counter = 0;
while(!dataFile.eof())
{
dataFile >> *precinct_num[counter];
for(int i = 0; i < 7; i++)
{
dataFile >> *num_votes[counter][i];
}
counter++;
}
//Print out the data
for(int j = 0; j < counter; j++)
{
cout << *precinct_num[j];
for(int i = 0; i < 7; i++)
{
cout << *num_votes[j][i];
}
}
dataFile.close();
cout << "End of file";
return 0;
}
bool openFileIn(fstream &file, char *name)
{
file.open(name, ios::in);
if(file.fail())
return false;
else
return true;
}
再次感谢!
【问题讨论】:
-
您遇到的具体问题是什么?
-
我认为您不太了解指针是什么。如果您想弄清楚指针是什么以及它们的作用,那么一个关于指针的好教程可能会有很长的路要走。
-
这有点像超高端商品的价格:如果你要问,他们就错了。有了指针你负责知道。