每次我 运行 代码时程序给出不同的输出
Program giving different output every time I run code
我创建了一个程序,它从文件中读取数字并将其存储在 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
.
因为你只为你的数组分配一个整数值,你会越界,这反过来会导致undefined behavior,这使得你的整个程序格式错误无效。
要分配 "array",您需要像 new int[n]
一样使用方括号。或者更好的是,使用 std::vector
.
我创建了一个程序,它从文件中读取数字并将其存储在 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
.
因为你只为你的数组分配一个整数值,你会越界,这反过来会导致undefined behavior,这使得你的整个程序格式错误无效。
要分配 "array",您需要像 new int[n]
一样使用方括号。或者更好的是,使用 std::vector
.