从输入文件读取整数,仅存储数组C 中的唯一整数

Reading integers from an input file, storing only the unique integers in the array C++

本文关键字:整数 数组 唯一 存储 输入 文件 读取      更新时间:2023-10-16

我已经陷入了几天的作业问题上。我做了一些研究,我得到了:

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

对于第二部分,使用大小而不是最大尺寸