-1

I am pretty novice at C++. Basically what I am trying to do is to read a file into any array and display it, but what happens is that a garbage values appears when running the code below. What exactly I am missing?

#include "stdafx.h"
#include<iostream>
#include<fstream>

using namespace std;

void main() {
    int array_size = 1024;
    char*array = new char[array_size];

    int position = 0;
    ifstream fin("Map.txt");
    if (fin.is_open()) {
        while (!fin.eof() && position < array_size) {
            fin.get(array[position]);
            position++;
        }
        array[position - 1] = '\0';

        cout << "Displaying array......" << endl << endl;

        for (int i = 0; array[i] != '0'; i++) {
            cout << array[i];
        }
    } else {
        cout << "File could not be opened" << endl;
    }
}
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
haitham hany
  • 33
  • 2
  • 11

1 Answers1

1

The main issue is that your for loop condition is wrong. You should not be comparing array[i] against '0' because that is the ASCII character 0 whose value is actually 48.

You want to compare array[i] against the "null-terminating character" which is '\0' whose value is 0.

Mohamad Elghawi
  • 2,071
  • 10
  • 14
  • Problems that can be resolved by fixing a typo should not be answered. They are not useful to anybody else. They need to be closed. – R Sahu Oct 23 '15 at 16:46