I have been reading some of the posts on reading integers from files but I have not seen any on reading integers from formatted files. I have a file which is a 6 X 6 matrix consisting of integers separated by tabs. I want to read each number into an array so I can later do computations on each array element and then print them out in a new 6 X 6 matrix. I have been working on some code but I am not sure if I am going in the right direction.

Here is how it is suppose to work.

1. Ask user of the name of the file to open (done)
2. Read the first line of the matrix of 6 integers separated by tabs into an array.
3. Compute the new value of each element in the array using the metrics.
4. Send the new values to another function which will write the new values to a file.
5. Repeat steps 2-5 until reaching the end-of-file.

Here is the code I am reusing from an earlier project that worked with strings. I might be way off on this one so please bear with me.

//metric values
  const int interface_speed = 25; //speed of the pc network cards
  const int hop_value = 5; //number of connections per node

void create_metrics(ifstream &fin, int number[])
{
 
   //write first row of numbers into the array
   while (fin >> number[array_size])
   {  
     //create new number
     for(int i =0; i<array_size; i++)
     {
         number[i] = (number/interface_speed)/hop_value;
     }

     //get all the integers from the file...
     while(fin.get(ch))
     {
       if(ch != ' ' && ch != '\n')//..until the next whitespace character or eof is found 
       {          
         number += ch; //add the value to number
         
       }
       else  //if a whitespace is found do the following
        {
        //calls the function create_matrix
          create_matrix(number);     
          //resets number to 0
          number = 0;
          //gets out of the loop 
          break;
        }
      }
     }             
}        

//writes the output to the output file as a matrix with the metrics added
void create_matrix(int &number) 
{
 //still working on this one

}

how big is number ? Is array_size the number of valid elements in the array? If that is true then line 9 is wrong because there is no such element as number[array_size] -- should be number[array_size-1]

why is that reading the file one character at a time? The >> will skip all white space (spaces and tab characters). Why not something like this:

int index = 0;
while(index < array_size && fin >> number[index] )
  index++;

The above will read the entire file until either end-of-file or the max number of elements in the array is reached.

line 39: >> void create_matrix(int &number)
That's wrong. number is an array of integers and what you have there is a reference to a single integer. You want this: void create_matrix(int number[])

This is what I have so far and it should be a little easier to understand. I have changed the variables array_size and read_array so they are easier to understand. The code is still not finished as I am still working on some of the logic (see functions create_metrics and create_matrix).

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <stdlib>
#include <iomanip>

using namespace std;

const int nodes = 6; //contains the numbers to be written to each line
const int matrix_size = nodes * nodes;  //contains all the intgers from the matrix
const int interface_speed = 25; //speed of the pc network cards
const int hop_value = 2; //number of connections per node


//function that takes the metrics and creates new values for the matrix
void create_metrics(ifstream &fin, int number[]);

//function that writes the output as a new matrix
void create_matrix(int number[]);

//opens the file or quits program and calls the create_metrics function
int main() 
{
    char filename[30];
    ifstream fin; //file stream object
    int number[matrix_size];   
    char q;
    
    //prompts the user for the file to test     
    cout << "Enter the name of the file you wish to open." 
            "If you type 'q', the program will terminate. "<<endl;
    cin >> filename;
    
    if(stricmp(filename, "q")== 0)//compares the user input to the letter q
    {
      cout <<"You have chosen to quit the program."<<endl;
      system("PAUSE");
      return EXIT_SUCCESS;
    }
    else(fin.open(filename));
      {
        create_metrics(fin, number);//call to getToken function
        fin.close(); //close input file
        system("PAUSE");
        return EXIT_SUCCESS;
      }
}


//reads integers from the file beginning at the first character and stops
//at spaces.  
void create_metrics(ifstream &fin, int number[])
{
   //write all integers from the file into the read array
   while (fin.good())
   {  
     for(int i = 0; i < matrix_size; i++) //
        fin >> number[i];
   } 
   //takes each number and performs calculations on it to create a new value 
   for(int i =0; i < matrix_size; i++)
   {
     number[i] = (number[i]/interface_speed)/hop_value;
     
     if(number[i] < 0)
        number[i] = number[-i]; //converts a number less than 0 to a negative value
   }
   
   create_matrix(number); 
                 
}        

//writes the output to the output file as a matrix with the metrics added
//still working on this function
void create_matrix(int number[]) 
{
  ofstream fout();
  fout.open("data.txt"); //opens an output file
 
 //this set of code is to write the data to the output file
 //after is writes 6 numbers  it is to go to the next line and write 6 more
 // numbers and continue to do this until it is done
  
  while(fout.good()) //
  {
   for(int i =0; i < matrix_size; i++)
     for(int j = 0; j < nodes; j++)
     {
       fout<<number[i]<<setw(5)<<endl;
     }
  } 
fout.close(); //close output file
}

In lines 65 & 66 I am trying to change any number less than 0 to a negative number. Will the method I have tried work?

In lines 75 - 93 I am trying to write only 6 numbers per line, is there a better way to do this than using a loop? Is there a function in the iomanip library that can do this.

lines 55-59 -- that is the wrong way to code such a loop. See the way I showed it in my previous post. It will not work the way you have it if end-of-file is reached before matrix_size number of characters.

Ancient Dragon lines 55-59 -- that is the wrong way to code such a loop. See the way I showed it in my previous post. It will not work the way you have it if end-of-file is reached before matrix_size number of characters.

I have made the changes you have suggested but now when it creates the data file, the file is way to large. It was almost 24 megs.

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

const int nodes = 8; //contains the numbers to be written to each line
const int matrix_size = nodes * nodes;  //contains all the intgers from the matrix
const int interface_speed = 25; //speed of the pc network cards
const int hop_value = 2; //number of connections per node


//function that takes the metrics and creates new values for the matrix
void create_metrics(ifstream &fin, int number[]);

//function that writes the output as a new matrix
void create_matrix(int number[]);

//opens the file or quits program and calls the create_metrics function
int main() 
{
    char filename[30];
    ifstream fin; //file stream object
    int number[matrix_size];   
    char q;
    
    //prompts the user for the file to test     
    cout << "Enter the name of the file you wish to open." 
            "If you type 'q', the program will terminate. "<<endl;
    cin >> filename;
    
    if(stricmp(filename, "q")== 0)//compares the user input to the letter q
    {
      cout <<"You have chosen to quit the program."<<endl;
      system("PAUSE");
      return EXIT_SUCCESS;
    }
    else(fin.open(filename));
      {
        create_metrics(fin, number);//call to getToken function
        fin.close(); //close input file
        system("PAUSE");
        return EXIT_SUCCESS;
      }
}


//reads integers from the file beginning at the first character and stops
//at spaces.  
void create_metrics(ifstream &fin, int number[])
{
   //write all integers from the file into the read array
   int index = 0;
   
  while(index < matrix_size && fin >> number[index] )
  index++;
   //takes each number and performs calculations on it to create a new value 
   for(int i =0; i < matrix_size; i++)
   {
     number[i] = (number[i]/interface_speed)/hop_value;
     
     if(number[i] < 0)
        number[i] = number[-i]; //converts a number less than 0 to a negative value
   }
   
   create_matrix(number); 
                 
}        

//writes the output to the output file as a matrix with the metrics added
//still working on this function
void create_matrix(int number[]) 
{
  ofstream fout;
  fout.open("data.txt"); //opens an output file
 
 //this set of code is to write the data to the output file
 //after is writes 6 numbers  it is to go to the next line and write 6 more
 // numbers and continue to do this until it is done
  
  while(fout.good()) //
  {
   for(int i =0; i < matrix_size; i++)
     for(int j = 0; j < nodes; j++)
     {
       fout<<number[i]<<setw(5)<<endl;
     }
  } 
fout.close(); //close output file
}

The code I suggested does nothing to the size of the file because it only reads the file, not write it.


line 64: >> number = number[-i];
-i is an illegal index into the array. what you meant is number[i] = -number[i]; The problem with creating such a huge file is located at lines 84-89. That is writing the same values matrix_size * nodes number of times, or 8^3 number of times.

line 59: If the file contains 6 X 6 = 36 number of integers why is matrix_size defined as 64? The loop starting on line 59 will process array elements 37-64 which have not been initialized with anything and just contain some random values.

void create_matrix(int number[]) 
{
  ofstream fout;
  fout.open("data.txt"); //opens an output file
 
 //this set of code is to write the data to the output file
 //after is writes 6 numbers  it is to go to the next line and write 6 more
 // numbers and continue to do this until it is done
  
   for(int i =0; i < matrix_size; i++)
   {
       if( (i % 6) == 0)
           fout << "\n";
       fout<<number[i]<< '\t';
   }
   cout << "\n";
   fout.close(); //close output file
}

The code I suggested does nothing to the size of the file because it only reads the file, not write it.


line 64: >> number = number[-i];
-i is an illegal index into the array. what you meant is number[i] = -number[i]; The problem with creating such a huge file is located at lines 84-89. That is writing the same values matrix_size * nodes number of times, or 8^3 number of times.

Lines 84 - 89 are suppose to write the new integer values into an output file. Those integers are to be written with eight rows and eight columns. The problem is I am still working on the code to get that to work.


The matrix is defined as a matrix of 64 values as it is a 8 X 8.

>>integers are to be written with eight rows and eight columns
I stopped the loop after it wrong over 1,000,000 data items. It was due mainly to that while loop because it was an infinite loop. The code I posted writes 6 numbers to a line, you can easily change that if you wish to however many you want by changing the line with the % operator.

Please re-read my previous post because I added a correction to write . There is the output

0	0	0	0	0	0	
0	0	0	0	0	0	
0	0	0	0	0	0	
0	0	0	0	0	0	
0	0	0	0	0	0	
0	0	0	0	0	0	
17179869	17179869	17179869	17179869	17179869	17179869	
17179869	17179869	17179869	17179869	17179869	17179869	
17179869	17179869	17179869	17179869	17179869	17179869	
17179869	17179869	17179869	17179869	17179869	17179869	
17179869	17179869	17179869	17179869

>> number = (number/interface_speed)/hop_value;
Depending on the value of number that formula may result in 0

>> number = (number/interface_speed)/hop_value;
Depending on the value of number that formula may result in 0

Somehow I missed the earlier post. But to answer this question, some of the numbers are going to be zero and that is not exactly right. There is only one diagnol where the numbers would be zero. All others are positive. When the program does the computation, it is suppose to take any number that is less than zero and make it negative. However, the output file results show the results are always positive. I'm still working on this.

The values are 0 because its doing integer math. 1/2 is 0 and the remainder is tossed into the bit bucket. If you want remainders than make the array float instead of int.

>> it is suppose to take any number that is less than zero and make it negative. However, the output file results show the results are always positive.

Simple algebra -- a negative negative is a positive. So -(-1) is +1. You must have read that requirement incorrectly because if you make a number less than 0 it is already negative. number[i] = -number[i]; //converts a number less than 0 to a negative value That creates a positive number, not a negative number. If number < 0 then its already negative, so you don't have to do anything to it.

Thank you for the help. I managed to finish the program.

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.