每次运行代码时,程序都会提供不同的输出

Program giving different output every time I run code

本文关键字:输出 运行 代码 程序      更新时间:2023-10-16

我已经创建了一个程序,该程序从文件中读取数字并将其存储在3个数组中,然后将其打印在另一个文件中。代码如下:

    #include <iostream>
    #include <cstdlib>
    #include <fstream>
        int main() {
            std::ifstream input("input.txt");
            input >> n;
            int* array1 = new int(n);
            int* array2 = new int(n);
            int* array3 = new int(n);
            for(int i = 0; i< n; i++){   
                input_file >> array1[i];
                input_file >> array2[i];
                input_file >> array3[i];
            }
            std::ofstream output("output.txt");
            for(int i = 0; i< n; i++){
                output << array1[i] <<"t";
                output << array2[i]<<"t";
                output << array3[i]<<std::endl;
            }
}

输入文件看起来像:5
1 2 3
3 4 5
5 6 7
7 8 9
9 10 11

每次我运行程序时,都会以不同的方式打印出输出的第二行,例如
1 9 10或
1 2 10或
1 9 3

有时它正确打印。任何帮助都将不胜感激。

问题很可能是您的分配:new int(n)分配一个整数值并将其初始化为值n

由于您仅分配一个数组的单个整数值,因此您会 ,而这将导致 undfined行为,这会使您的整个程序不适 - 形成无效的。

要分配"数组",您需要使用new int[n]中的方形托架。或者更好,请使用std::vector