簡體   English   中英

無法在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傳遞到函數中,並使用push_back將從文件中讀取的內容放入向量中。

與此同時,

 cout<<array1<<endl;
 cout<<array2<<endl;

打印數組地址。 因此是可以預期的。 您需要遍歷數組以打印出內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM