给出随机数的数组元素c ++

时间:2018-12-05 21:59:43

标签: c++

int main() {

    ifstream inFile("nums-1.txt");

    // Checks if the file opened successfully
    if (inFile.fail())
        cout << "Fail to open the file!" << endl;

    int value = 0, searchForInt, size = 0;
    int numsArray[size];

    // Assigns each values to the array and determine size
    while (inFile >> value)
    {
        numsArray[size] = value;
        size++;
    }

    cout << "Enter an integer to search for:" << endl;
    cin >> searchForInt;

    cout << "This array has " << size << " items." << endl;
    cout << "The array entered by the user is as follows: ";

    for (int i = 0; i < size; i++)
    {
        cout << numsArray[i] << " ";
    }


    inFile.close();
    return 0;
}

输出:

The array entered by the user is as follows: 22 -4 5 100 39 20 -1348122768 32767 -1348122768 32767 -1348122768 32767

我要输出的内容:

The array entered by the user is as follows: 22 -4 5 100 39 20 88 10 55 3 10 78 <- These are the values in the secondary file.

我在打开的文件(nums-1.txt)中有几个12个值,并且读取时没有问题。问题是当我尝试通过for循环输出整个数组时,它将一直显示到第8个元素,然后才显示元素9-12的随机数。

1 个答案:

答案 0 :(得分:1)

与其他评论一样,请使用std::vector。将数字加载到数组中时,您正在使用未定义的行为。

int value, searchForInt = 0;
std::vector<int> numsArray;

while (inFile >> value)
{
    numsArray.push_back(value);
}
// ...
cout << "This array has " << numsArray.size() << " items." << endl;
cout << "The array entered by the user is as follows: ";

for (int i = 0; i < numsArray.size(); i++)
{
    cout << numsArray[i] << " ";
}