Bosco
Bosco

Reputation: 45

How to put values from a file into an array

So I've been working on this program that is supposed do some operations with numbers in an array. But those operations aren't the problem. The problem is that I can't seem to understand how to put 4 numbers from an input file into an array.

When I check it using an output statement with the array and the index 2, it outputs zero. Instead of the number 4.

All the numbers.txt file would include are: 2 4 3 5

#include <iostream> //cin, cout, endl
#include <iomanip>  //manipulators such as setw, setprecision
#include <fstream>  //File I/O
#include <cmath>    //math operators like pow
#include <string>   //string
#include <cassert>  //function assert

using namespace std;
typedef unsigned int uint;
const string fileName = "numbers.txt";


int main()
{
    uint arrayWithNumbers[100];
    uint currentNumber = 0;
    uint limiter = 0;
    ifstream inData;
    inData.open(fileName);

    if(inData)
    {
        while(inData >> currentNumber)
        {
            arrayWithNumbers[limiter] = currentNumber;
            limiter++;
        }//while for array processing
    }//if check for file

    inData.close();
    cout << arrayWithNumbers[2] << endl;

}//main

Upvotes: 3

Views: 71

Answers (1)

skratchi.at
skratchi.at

Reputation: 1151

As you limit your read operation inData >> currentNumber to the type of uint, it will fail to read a char. A comma is a char. This leads then to an end of the loop.

And you are lucky the output shows 0. You access uninitialized memory, which I strongly advice you should not do.

uint arrayWithNumbers[100] = {0};

Upvotes: 1

Related Questions