每次运行代码时,程序都会提供不同的输出
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
。
由于您仅分配一个数组的单个整数值,因此您会 ,而这将导致 undfined行为,这会使您的整个程序不适 - 形成无效的。
要分配"数组",您需要使用new int[n]
中的方形托架。或者更好,请使用std::vector
。
相关文章:
- 在多次运行中获得一致的callgrind输出
- 在Qt Creator中,如何在连接到正在运行的进程后查看控制台输出
- 编译并运行后,输出未出现在 Visual Studio 代码中
- C++ 每次运行程序时我都会"nan"输出的问题
- 如何在不丢失输出的情况下杀死/停止终端中正在运行的进程?
- 如何使用 c++ libboost 运行进程并获取其输出?
- 在集成终端上运行vscode lldb调试器时,如何获取程序的输出?
- 获取使用p4api运行的Perforce命令的输出
- 为什么如果我从键盘输入EOF克里昂不要在运行窗口打印程序的输出?
- 运行时错误,尽管我得到了预期的输出
- 使用 ' ios::sync_with_stdio(0)' 测试运行时的差异时,为什么我的输出是碎片化的?
- c++:if 语句无法正常运行,并继续执行无效输出
- 每次运行时,相同的程序都会给出不同的输出
- 在代码仍在 C++ QT 中运行时显示打印输出
- 在结束运行之前获取 c++ 中的 shell 命令输出
- 运行时 kinect 输出的 3D 可视化
- 在 Windows 命令行中运行.exe在使用 2 种相同方式执行时会产生不同的输出
- cmake googletest不运行测试,没有输出
- 如何将控制台输出的文本颜色更改为红色,但如果从Powershell或CMD运行,背景将保持相同的颜色
- 如何运行批处理文件和读取输出