从文件中读取整数并将其存储在数组C ++中 [英] Reading integers from file and store them in array C++
本文介绍了从文件中读取整数并将其存储在数组C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码,但是我遇到了第一个数字无限循环
我想从他的文件中读取整数并将它们存储在数组中
this my code but i get infinite loop with the first number
I want to read the integers fromt he file and store them in the array
文件包含:
8 5 12 1 2 7
8 5 12 1 2 7
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int n = 0; //n is the number of the integers in the file ==> 12
int num;
int arr[100];
ifstream File;
File.open("integers.txt");
while(!File.eof())
{
File >> arr[n];
n++;
}
File.close();
for(int i=0;i<12;n++)
{
cout << arr[i] << " ";
}
cout << "done\n";
return 0;
}
请帮助
推荐答案
我同意@ravi,但我为您提供一些提示:
I agree with @ravi but I some notes for you:
如果您不知道其中有多少个整数文件,并且文件仅包含 个整数,您可以执行以下操作:
If you don't know how many integers are in the file and the file contains only integers, you can do this:
std::vector<int>numbers;
int number;
while(InFile >> number)
numbers.push_back(number);
您需要#include< vector>
最好先读取文件中有多少个整数,然后使用循环读取它们:
it would be better if you read how many integers are in the file and then use loop to read them:
int count;
InFile >> count;
int numbers[count]; //allowed since C++11
for(int a = 0; a < count; a++)
InFile >> numbers[a];
注意:我没有检查成功阅读,但这是一个好习惯。
这篇关于从文件中读取整数并将其存储在数组C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文