Hello! I need to read 50 intergers from a text file and put them in an array.Then I have to seperate the numbers into different arrays to see if they are even or odd.

This is what I have and all I get as a cout is a place in memory like -862527. I cout because i just want to see if I even get to read the numbers at least but I'm doin it wrong.

Any help or tips would be welcomed!

#include "StdAfx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;


int main (){
    ifstream infile;
    int num=0;
    int list[51];
    int even [51];
    int odd [51];

infile.open("infile.txt");

    for (int i=0;i<51;i++)
    {int x=0;
        infile>>list[51];
        cout<<list[51];
            system ("pause");
    }


    system ("pause");
    return 0;

}

You need to check that the file was opened successfully. Put this after line 16

if( !infile.is_open())
{
   cout << "Error opening file\n";
   return 1;
 }

line 19: move the declaration of x up outside the loop so that it can be used to index into the array.
line 20: use the index value instead of 51 infile>>list[x++]; Change line 21 like that too.

Thnz for the taking time!
But nothing happens when I try to cout It just gives me a negative number like -594242

did you change lines 19 and 20 like I said?

Here's a shortened version of your program:

int main (){
    ifstream infile;
    int list[51];
    infile.open("infile.txt");
    for (int i=0;i<51;i++){
        infile>>list[i];
        cout<<list[i]<<" ";
    }
    return 0;
}

Indeed, lines 20 and 21 were messing your program up.

Yes sir I did:

#include "StdAfx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main (){
    ifstream infile;
    int num=0;
    int list[51];
    int even [51];
    int odd [51];
infile.open("infile.txt");

if( !infile.is_open())
{
   cout << "Error opening file\n";
   return 1;
 }

 while(!infile.eof()){
    int x=0; 
    for (int i=0;i<x;i++)
    {
        infile>>list[x++];
        cout<<list[x++];
            system ("pause");
    }
 }
 system ("pause");
    return 0;
}

The loop is all wrong. Don't assume there will be 51 numbers in the file. What will happen if there are only 10 numbers? or 100 numbers? It's not necessary to specifically test for eof() because the file stream will return NULL when eof() or an error is encountered.

 while(x < 51 && infile >> list[x]){
    cout<<list[x];
    ++x;
 }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.