从文件中读取整数并将它们存储在数组 C++ 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26979236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading integers from file and store them in array C++
提问by Error-F
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
这是我的代码,但我得到了第一个数字的无限循环
我想从他的文件中读取整数并将它们存储在数组中
the file contains:
该文件包含:
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;
}
Any help please
请任何帮助
回答by Quest
I agree with @ravi but I some notes for you:
我同意@ravi,但我要给你一些注意事项:
If you don't know how many integers are in the file and the file contains onlyintegers, you can do this:
如果您不知道文件中有多少个整数并且文件只包含整数,您可以这样做:
std::vector<int>numbers;
int number;
while(InFile >> number)
numbers.push_back(number);
You need to #include<vector>
for this.
你需要#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];
Note: I didn't check for successful read, but it is a good practice to do so.
注意:我没有检查是否成功读取,但这样做是一个很好的做法。
回答by ravi
Your loop should be:-
你的循环应该是:-
for(int i=0; i < n ; i++)
{
cout << arr[i] << " ";
}