我有两个文件,我应该将它们都输入到数组中。 其中之一是:
2
3
4
5
7
8
第二个是
2
4
5
6
7
8
2
3
4
5
7
8
(虽然长了很多,但没关系)。我需要一个包含前 6 个数字的数组,然后我应该检查第二个文件中的前六个数字是否与第二个数组中的数字相同,是否与接下来的六个数字相同等等(比如检查彩票中奖者)。 我想我应该将一个文件中的数字加载到多个数组中,但我不知道该怎么做,而且我在任何地方都找不到它。
我目前拥有的第一个数组的代码是:
#include<iostream>
#include<fstream>
using namespace std;
int main(){
int numbers[6];
int count = 0;
ifstream inputFile;
inputFile.open("Numbers.txt");
while (count < 20 && inputFile >> numbers[6]){
count++;
inputFile.close();
for (count=0; count < 20; count++)
cout << numbers[count];}
return 0;
}
另一个问题是,它没有正确显示数字,而是显示了 6 次“-858993460”——尽管我的代码基本上是从一本书上复制的……
我的代码有什么问题,如何输入第二个文件?
最佳答案
你的主要问题是在你的循环中做一些不应该存在的事情。该循环应该为它从文件中读入的每个值运行一次。 完成之后,您应该关闭文件并打印结果。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int numbers[6];
int count = 0;
ifstream inputFile;
inputFile.open("Numbers.txt");
if(!inputFile.is_open()) // always check for errors
{
std::cerr << "ERROR opening input file:" << std::endl;
return 1; // error
}
// make sure count < 6 so you don't overflow your array
while(count < 6 && inputFile >> numbers[count])
{
count++;
// inputFile.close(); // don't close the file yet!!
//for(count = 0; count < 20; count++) // don't output yet!!
// cout << numbers[count];
}
// now close your file and output what you have
inputFile.close();
for(count = 0; count < 6 /* not 20!! */; count++) // don't output yet!!
cout << numbers[count] << '\n';
return 0;
}
关于c++ - 在 C++ 中将文件输入到多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27327704/