array jibberish

So everyone knows when you try to print something in an array that doesnt belong, the screen prints out weird stuff. I made a program that takes a file, fills an array with 10 numbers, and prints only distinct numbers. So if there's a repeated number, the program replaces that number with a space. Once that's done, the program finally prints out what's left in the array which should be only distinct numbers. Anyway, here's my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <cstdlib>
#include <iostream>
#include <fstream>

const int MAX = 10;

using namespace std;

int main()
{
    int i, j, num[MAX];
    ifstream infile;
    infile.open("data.txt");

    if(!infile.is_open()) {
        cout << "\nERROR: Unable to open file" << endl;
        system("PAUSE");
        exit(1);
    }

    i = j = 0;
    while(!infile.eof() && infile >> num[i])
        i++;

    for(i=0; i<9; i++)
        for(j=i+1; j<=9; j++) {
            if(num[i]==num[j])
                num[j] = ' ';
        }

    for(i=0; i<=9; i++)
        if(num[i]!= ' ')
            cout << num[i] << " ";

    infile.close();
    system("PAUSE");
    return 0;
}


Let's say I want to make an array of 100 slots but only have the program take in 50 numbers (because there are only 50 numbers in the file). When I do that, I get the jibberish. The program works fine when I only make a file with exactly the amount of numbers that my array can hold. It actually still works with any size but I dont want the jibberish. What must be fixed?
Last edited on
When you have to deal with variable number of elements, you use vectors:
1
2
3
4
5
6
7
8
9
10
11
vector<int> numbers;
int number;
while (infile >> number)numbers.push_back(number);
for(size_t i=0  ; i<numbers.size(); i++)
for(size_t j=i+1; j<numbers.size(); j++)
{
    if(numbers[i]==numbers[j])
    {
        numbers[j] = 0;
    }
}


Also, you can't assign a "space" to an int variable - what happens is that the character will be converted to an integer (that would be 32 for a space in ASCII).
Last edited on
Here:
1
2
while(!infile.eof() && infile >> num[i])
        i++;

Change i to another variable name, possibly arraySize. Then in your loops, loop until i < size. This will eliminate all of that "gibberish" because you quite frankly don't output it.
Greatly appreciate your help, the both of you! Program works efficiently and neatly now.
Topic archived. No new replies allowed.