Read from file into an array one integer at a time

After entering a file name, I need to read the contents of that file into an array. I am having trouble reading one integer at a time from the file. In the text file I will be reading, the fist two numbers on the first line I want to assign as n=first#, m=second#. After that, I want to create a mx4 array given by the next m lines with 4 numbers per line. Once I know how to read one character at a time, I will be able to fill in my array.

Sample .txt file to be read:
4 5
1 2 10 4
2 4 9 5
1 4 11 6
1 3 12 7
3 4 13 8

----------------------------------------

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
39
40
41
42
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// Variables
int n,m;
string myfile; 
ifstream testfile;


int main()
{  
   cout << "Enter file name: ";
   cin >> myfile;                  //read in file name
   testfile.open(myfile.c_str());  //open file
   if (!testfile)                  //test to see if file is open
   {
      cout << "Error opening file\n";
      system("pause");
      return -1;
   }

   while (!testfile.eof())         //while file is open and not at the end
   {   
   // n = first # of first line in testfile;
   // m = second # of first line in testfile;   
   int array[m][4];
   // array[0][0] = first # of second line in file
   // array[0][1] = second # of second line
   // array[0][2] = third # ...
   // array[1][0] = first # of third line in file 
   //...
   }

   testfile.close();  

 system("PAUSE");
    return EXIT_SUCCESS;
}
Last edited on
you read from files the same way you read from cin. testfile >> n;
also, you don't need the while loop.
Thanks for the help! I got it to work.
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>
#include <string>

using namespace std;

// Variables
int n,m;
string myfile; 
ifstream testfile;


int main()
{  
   cout << "Enter file name: ";
   cin >> myfile;                  //read in file name
   testfile.open(myfile.c_str());  //open file
   if (!testfile)                  //test to see if file is open
   {
      cout << "Error opening file\n";
      system("pause");
      return -1;
   }
   else
   {
       testfile >> n >> m;
       int ForwardStar[m][4];   // Create a m x 4 matrix
       for (int i=0;i<m;i++)
           for (int j=0; j<4; j++)
               testfile >> ForwardStar[i][j]; 
   }

   testfile.close();  

 system("PAUSE");
    return EXIT_SUCCESS;
}

Topic archived. No new replies allowed.