在c++中从.txt文件加载数组时遇到问题
Trouble loading array from .txt file in C++
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
const int MAX=100;
//Declare Functions
void loadFile(istream &input_file, int arr[], int maxLength, int& length);
//Main Function
int main()
{
ifstream in_file1;
ifstream in_file2;
in_file1.open ("input1.txt");
in_file2.open ("input2.txt");
int array1[0], array2[0];
int length;
loadFile (in_file1, array1, MAX, length);
for (int i = 0; i <= length; i++)
{
cout << array1[i] << endl;
}
cout<<endl<<endl;
loadFile (in_file2, array2, MAX, length);
for (int i = 0; i <= length; i++)
{
cout << array2[i] << endl;
}
return 0;
}
//Function Definitions
void loadFile(istream &input_file, int arr[], int maxLength, int& length)
{
int i;
int input;
{
for (i=0; i<maxLength; i++)
{
if (!input_file.eof())
{
input_file>>input;
arr[i]=input;
length=i;
}
}
}
}
这是我的新代码。它仍然在数组后面打印一串不在文件中的数字。我离这儿近吗?
输出:-26
128
184
-4
-51
129
-93
199
115
-92
16
0
-64
56
5
112
-20
160
-56
148
94
18
145
155
178
83
-57
103
-68
69
-53
80
148
131
-82
1
102
-50
192
27
32
-63
34
150
160
160
137
-53
119
-64
-80
186
144
-78
-1
62
-72
86
127
40
53
-93
41
45
194
-19
118
53
31
-52
-27
150
-31
86
-29
34
103
4
-92
90
18
13
49
-57
-51
-7
78
62
97
15
122
154
172
9
-5
108
-33
-33
-60
88
89
190
171
109
39
111
-55
-11
160
16
68
172
168
-64
-14
-15
142
-16
-16
为什么它仍然打印最后一个数字两次?谢谢你的帮助
int array1[0], array2[0];
数组的长度为0
。你的意思可能是:
int array1[MAX], array2[MAX];
你必须为你的数组分配内存以便加载内容。
您可以将vector
s传递到函数中,并使用push_back
将从文件中读取的内容放入向量中。
cout<<array1<<endl;
cout<<array2<<endl;
打印数组地址。这是意料之中的。您需要循环遍历数组以打印出内容。
相关文章:
- 创建结构的数组时遇到分段错误
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 打印问题.我在数组中打印值时遇到一些问题
- C++ 填充数组时遇到问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 存储另一个函数返回的布尔数组时遇到问题
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 尝试通过多个函数移动数组,但遇到了我不知道如何修复的错误
- 对数组进行排序时遇到问题。为什么我的数组无法正确排序?
- 如果 strlen 在 char 数组之间遇到空格,它会怎么做
- 分割故障 - 遇到问题,创建新的数组实例
- 在C++中将动态数组的大小加倍时遇到问题
- 在C++的数组中查找最低值时遇到问题
- 访问对象数组中的对象时遇到问题
- 我在将 cv::Mat 保存到 1D 数组时遇到问题
- 我在使用 cin.getline() 从用户那里获取 3 个字符串并使用指针数组来存储它们时遇到问题
- 我在C++从函数中的用户获取输入、添加到数组和打印该数组时遇到问题
- 在打印出动态分配的数组中的前两个数字时遇到问题,其他数字工作正常
- 在二维结构数组C++遇到问题