簡體   English   中英

如何從文本文件中讀取整數並將其存儲在數組中?

[英]How to read integers from a text file and store them in an array?

我有一個名為example.txt的文件,其中包含7個這樣格式化的整數,

1個

2

3

4

5

6

7

我的代碼是

#include<iostream>
#include<fstream>

using namespace std;

int main() {

int arr[7];

ifstream File;
File.open("example.txt");

int n = 0;
while (File >> arr[n]) {
    n++;
}
File.close();

for (int i = 0; i < 7; i++) {
    cout << arr[i] << endl;
}

return 0;
}

該代碼有效,因為我已經知道文本文件中有多少個整數。 如果我不知道文件中有多少個整數,我應該在代碼中進行哪些更改以確保其有效? 換句話說,如果有人要更改文本文件中的整數數量,如何確保我的代碼有效?

使用std::vector而不是固定大小的數組。

使用現有代碼,然后可以使用push_back在向量的末尾添加項目。

或者,您可以使所有的怪胎並使用std::copystd::istream_iteratorstd::back_inserter 確實,我不建議這樣做,但看起來確實令人印象深刻。 這樣做很有趣。

您在那里幾乎符合C ++。

因此,我花了一些時間來更改代碼的幾行,並用vector代替C樣式的數組。 那是使它真正不含C的唯一缺失:)。 更改內容時,請參閱****注釋。

每次都使用vector ,特別是在您不知道列表大小的情況下(尤其是您知道大小),因為您可以在開始時reserveresize或創建具有適當尺寸的vector。

#include<iostream>
#include<fstream>
#include<vector>   // ****

using namespace std;

int main() {

vector<int> arr;   // ****

ifstream File;
File.open("example.txt");

int n;                     // ****
while (File >> n) {        // ****
    arr.push_back(n);      // ****
}
File.close();

for (auto n : arr) {      // ****
    cout << n << endl;    // ****
}

return 0;
}

使用-std=c++11標志對其進行編譯。

暫無
暫無

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

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