从输入文件读取整数,仅存储数组C 中的唯一整数
Reading integers from an input file, storing only the unique integers in the array C++
我已经陷入了几天的作业问题上。我做了一些研究,我得到了:
#include<iostream>
#include<fstream>
#include<string>
#include<array>
using namespace std;
const int MAX_SIZE = 100;
bool RepeatCheck(int storage[], int size, int checker);
int main()
{
ifstream input("input.txt");
if (!input) // if input file can't be opened
{
cout << "Can't open the input file successfuly." << endl;
return 1;
}
int storage[MAX_SIZE];
int inputCount;
int checker;
while (!input.eof())
{
for (int i = 0; i <= MAX_SIZE; i++)
{
input >> checker;
if (!RepeatCheck(storage, MAX_SIZE, checker))
{
input >> storage[i];
}
}
}
// print array
for (int i = 0; i < 100; i++)
{
cout << storage[i] << " ";
}
return 0;
}
bool RepeatCheck(int storage[], int size, int checker)
{
for (int i = 0; i <= MAX_SIZE; i++)
{
if (storage[i] == checker)
{
return false;
}
}
}
我的输入文件需要填充由空白或新行分隔的整数:
1 2 2 3 5 6 54 3 20 34 5 75 2 46 3 3 4 57 6 7 8
我需要从文件中读取整数并将它们存储在存储[]数组中,仅当它们尚未在数组中。
它没有做我需要做的事情。请查看我的代码,并告诉我逻辑错误在哪里。非常感谢。
如果允许std::set
,请使用它而不是进行自己的重复检查。
对于您的代码,问题发生在这里:
while (!input.eof())
{
//for loop not needed
for (int i = 0; i <= MAX_SIZE; i++) //increment regardless whether input is successful or not?
{
input >> checker; //take in a number
//if the number is not repeated
if (!RepeatCheck(storage, MAX_SIZE, checker))
{
input >> storage[i]; //read in another number to put it?
}
}
}
也在这里
bool RepeatCheck(int storage[], int size, int checker)
{
for (int i = 0; i <= MAX_SIZE; i++)
//check all values in the array regardless whether it has been used or not?
//should just check until the end of used space, which is what size is meant for
{
if (storage[i] == checker)
{
return false;
}
}
//there should be a return true here right?
}
请查看此链接,以了解为什么(!iostream.eof())
被认为是错误的。
第一部分应该像这样:
int i = 0;
while (input >> checker)
{
if (!RepeatCheck(storage, i, checker))
{
storage[i] = checker;
++i;
}
}
对于第二部分,使用大小而不是最大尺寸
相关文章:
- 从二进制文件中读取整数数组
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 从两个 4x64 位整数数组中获取取模
- 字符到整数数组
- 从函数参数 [C++] 复制整数数组
- 指向整数数组和打印总和的指针
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 线程安全整数数组?
- 整数数组中最长的回文
- 在大整数数组中查找子数组
- 查找整数数组中最接近的数字
- 创建<int>对整数数组指针的矢量引用 (C++)
- 整数指针数组的元素是否可以指向整数数组?
- 如何将整数数组相乘得到一个数字?
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 将文本文件读入整数数组