如何从文本文件中读取整数并将其存储在数组中? [英] How to read integers from a text file and store them in an array?

查看:190
本文介绍了如何从文本文件中读取整数并将其存储在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为example.txt的文件,其文件格式为7个整数

I have a file named example.txt with 7 integers formatted as such,


1

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;
}

此代码有效,因为我已经知道文本文件中有多少个整数。如果我不知道文件中有多少个整数,该如何更改代码以确保其正常工作?换句话说,如果有人要更改文本文件中的整数数量,那么如何确保我的代码可以正常工作?

This code works, because I already know how many integers are in the text file. What should I change in the code to make sure it works if I don't know how many integers are in the file? In other words, if someone were to change the number of integers in the text file, how do I make sure my code works?

推荐答案

您在那里几乎符合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.

这篇关于如何从文本文件中读取整数并将其存储在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆