且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从文本文件中读取整数并将其存储在数组中?

更新时间:2023-08-29 08:42:04

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

you were almost C++ compliant there.

因此,我花了一些时间来更改代码的几行,用向量。那是使它真正不含C的唯一缺失:)。更改内容时,请参见 **** 注释。

So I took the time to change a few lines of your code replacing the C-style array by a vector. That was the only thing missing to make it really C-free :). See the **** comments when I changed stuff.

使用 vector 每次,特别是在您不知道列表大小的情况下(即使您知道大小,因为您可以保留调整大小或在开始时创建具有适当尺寸的向量。

Use vector everytime, specially when you don't know the size of the list (and even if you know the size since you can reserve or resize or create the vector with the proper dimension at start.

#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 标志对其进行编译。

Use -std=c++11 flag to compile it.