【发布时间】:2018-04-13 23:39:21
【问题描述】:
作为我作业的一部分,我需要打开一个文件,然后将信息读入 3 个数组。这些信息分为 3 个不同的列,第一个是国家代码名称(是字符串),第二个是人口(是 int),第三个是国家的全名。以下是文件几行的示例:
- AU 20090437 澳大利亚
- BR 186112794 巴西
- BU 7262675 保加利亚
- 加拿大 32805041 加拿大
- CN 1306313812 中国
- DO 8950034 多米尼加共和国
到目前为止我有:
void readCntrData(string [], int [], string[], int &size, const int maxSize);
int main()
{
const int COUNTRIES = 200;
// maximum size of arrays
int size = 0;
string cntrCodes[COUNTRIES];
int cntrPopulation[COUNTRIES];
string cntrNames[COUNTRIES];
string inputFileName = "countries.txt";
ifstream inputFile;
inputFile.open(inputFileName.c_str());
if (inputFile.fail())
{
cout << "\n\tPlease check the name of the input file and \n\ttry again later!\n";
exit(EXIT_FAILURE);
}
int index = 0;
while (index < COUNTRIES && inputFile >> cntrCodes[index] >> cntrPopulation[index] >> cntrNames[index] ) {
index++;
}
size = index;
if (size == COUNTRIES && !inputFile.eof()){
cout << "\n\tThe input file \"" << inputFileName <<
"\"is too big: \n\tit has more than " << COUNTRIES << " items!\n";
exit(EXIT_FAILURE);
}
inputFile.close();
}
这里的问题很少有国家有两个部分名称,我的代码在国家名称有两个部分的地方中断。我不知道如何忽略那里的空间并阅读整个名称。
感谢任何反馈。
【问题讨论】:
-
考虑一个包含三段数据的结构数组,而不是三个并行数组。让一切保持同步变得更加容易。
-
不要使用数组。不要使用“并行数组”。使用结构或类的向量。
-
幸运的是,多词标记位于行尾。你可以
file >> token 1 >> token2 && getline(file, token3) -
while (index < COUNTRIES && inputFile >> cntrCodes[index] >> cntrPopulation[index] >> cntrNames[index] )干得好 -
@NeilButterworth 不幸的是我还没有了解结构和类。谢谢你的建议