Ive used the search function just found one thing I needed more detailed help

I need to a read file of float numbers no more than 100 numbers but can be less than 100 into an array

I have made sample file contain 1 2 3

I have the following code

#include <iostream>
#include <fstream>
using namespace std; 

const int Max_Size = 100;

int main()
{
    ifstream inFile;
    float array[Max_Size];
    int i;
    string fileName;
    
    cout<<"Enter the name of the input: ";
    cin>>fileName; 
    
    inFile.open(fileName.c_str());
    
    for(i=0; i<Max_Size; i++)
    {        
          inFile>>array[i];
          cout<<array[i];
}
    
 
             
    inFile.close();

I also have to keep a counter of all numbers in the file

That for loop is incorrect. What you want is to read until either Max_Size has been read or until end-of-file

int i = 0;
while(i < Max_Size && inFile>>array[i] )
   ++i;

Thanks and then I use the for loop to display the data?


If i use the for loop it displays the numbers but then a bunch of junk afterward ? i only have 3 float numbers in there atm

you need to post that code. Make sure the loop does not increment past the number of floats that were read, not Max_Size. The value of i in the loop I posted is the number of floats read.

for(int j = 0; j < i; j++)
{
   // blabla
}

Thanks! Works like a charm

here is my code so you dont think I was bumming you for answers
and changed i to the number of floats read and i to the array

#include <iostream>
#include <fstream>
using namespace std; 

const int Max_Size = 100;

int main()
{
    ifstream inFile;
    float array[Max_Size];
    int amountRead = 0, i;
    string fileName;
    
    cout<<"Entner the name of the input: ";
    cin>>fileName; 
    
    inFile.open(fileName.c_str());
    
    while(!inFile.eof() && inFile>>array[amountRead])
    {
                     amountRead++;
                     
                     }
    
    for(i=0; i<amountRead; i++)
    {
             cout<<array[i];
             }
    
  
  
   
    return 0;
}

Any idea how I would implement this into an 2-D Array

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.