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

时间:2017-12-06 03:14:34

标签: c++ arrays ifstream

我已经被困在这个家庭作业问题上了好几天了。我做了一些研究,我得到了这个:

#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 5 4 3 20 34 5 7 5 2 4 6 3 3 4 5 7 6 7 8

我需要从文件中读取整数并将它们存储在storage []数组中,只要它们不在数组中。

它没有做我需要做的事情。请查看我的代码并告诉我逻辑错误在哪里。非常感谢。

1 个答案:

答案 0 :(得分:0)

如果允许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?
}

请查看此link,了解(!iostream.eof())被视为错误的原因。

第一部分应如下所示:

int i = 0;
while (input >> checker)
{
    if (!RepeatCheck(storage, i, checker))
    {
        storage[i] = checker;
        ++i;
    }
}

对于第二部分,使用size而不是max size