项目介绍
-
这个项目将实现一个虚拟初始化数组并测试它的正确性。
-
使用三个整数数组:data[]、forward[]和backward[],每个数组包含100个元素。
-
txt文件包含一组成对的:where ,what。使用虚拟初始化将值what存储在数据数组的位置中。例如data[where] = what。
-
这个序列被一对-1 -1终止。
-
后面跟着一个单整数值序列probe。对于每个这样的值,您需要测试data[probe]是否已经初始化,并打印以下两条消息之一:
- 位置probe未初始化。
- 位置探probe已初始化为数值data[probe]
-
该序列以值-1结束。
举个例子:
读取一个txt文件,右侧的一列为data[x]数组中x的位置,左侧的一列为数组的值。
数组的读取到-1,-1终止。
probe为:
5,17, 24,42,99
序列以值-1结束。
读取的txt部分如下:
经过程序输出的格式应为:
Position 5 has not been initialized.
Position 17 has …
Position 24 has …
Position 42 has …
Position 99 has …
代码实现
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//use three integer arrays, data[], forward[] and backward[] each containing 100 elements
const int MAXWORDS = 100;//max words in array
int Array_data[MAXWORDS];
int Array_forward[MAXWORDS];
int Array_backward[MAXWORDS];
int main()
{
string a;
cout << "Please enter the filename: " << endl;
cin >> a;
ifstream read;
read.open(a.c_str());
if (!read)
{
cout << "Can't open file" << endl;
exit(1);
}
int index = 1;
int vcn = 0;//valid count number
int x = 0, y = 0;
while (!read.eof())
{
while (index < 100)
{
if (read.fail())break;
read >> y;
read >> x;
if (x == -1 && y == -1)// terminated by the value -1
break;
vcn++;
Array_data[x] = y;//where what
Array_forward[vcn] = x;
Array_backward[x] = vcn;
index++;
}
int i = 0;
while (i < 100) {
read >> x;
if (x == -1)// terminated by the value -1
break;
i++;
if (Array_backward[x] > 0 && Array_backward[x] <= vcn && Array_forward[Array_backward[x]] == x)
{
cout << "Position " << x << " has been initialized to value " << Array_data[x] << "." << endl;
}
else
{
cout << "Position " << x << " has not been initialized." << endl;
}
}
}
read.close();
return 0;
}
程序输出如下:
)