This is the first program I have had to do in 5 years so please don't be surprised by some of the mistakes. I am creating a program that will open a file and sort the integers inside that file using Insertion sort. There are 12 files and each as a different number of integers to sort. I am having multiple problems but right now I would like help with writing the contents of the file to the array. I get errors stating I am using two different types, char to int. Here is the code.

#include <cstdlib>
#include <iostream>
#include <math.h>
#include <fstream>
#include <iomanip>
#include <sstream>

using namespace std;


void insertion_sort(int numbers[], int* array[]);

int main()
{
    int SIZE;
    int array[SIZE]; //array sized for each file input
    int numbers;
    ifstream infile; //input data file
    ifstream fin;    // file data opject
    char filename[50];
        
    cout << "Enter the name of the file you wish to open. "<<endl;
    cin >> filename;
    fin.open(filename);
    
    if(infile.bad()) //checks to see if the file will open
    {
      std::cerr <<"Error. Could not open datafile Num8.txt" <<endl;
      exit(8);
    }
    
    if(filename == "Num8.txt") //depending on the input file used, the size of the array will change
       SIZE = 8;
       else if(filename == "Num16.txt")
               SIZE = 16;
          else if(filename == "Num32.txt")
                  SIZE = 32;   
             else if(filename == "Num64.txt")
                     SIZE = 64;
                else if(filename == "Num128.txt")
                        SIZE = 128;
                   else if(filename == "Num256.txt")
                           SIZE = 256;
                      else if(filename == "Num512.txt")
                              SIZE = 512;
                         else if(filename == "Num1024.txt")
                                 SIZE = 1024;
                            else if(filename == "Num2048.txt")
                                    SIZE = 2048;
                               else if(filename == "Num4096.txt")
                                       SIZE = 4096;
                                  else if(filename == "Num8192.txt")
                                          SIZE = 8192;
                                     else if(filename == "Num16284.txt")
                                             SIZE = 16284;
                                        else
                                           cout << "You entered a file not accessable by this program"<<endl;
    
        
      while(!infile.eof()) // the contents of the file are read into the array until the end of file is reached
      {
       fin.getline(infile,SIZE); //write contents of file to array
       insertion_sort(numbers, array); //insertion sort function is called
      }
     
    
    infile.close();
    system("PAUSE");
    return EXIT_SUCCESS;
}

void insertion_sort(int numbers[], int* array[SIZE])
{
     int i;
     int j;
     int key;
     int SIZE;
     int count = 0;
     for (i=1; i < array; i++)
     {
         key = numbers[i];
         j = i;
         while((j > 0) && (numbers[j-i] > key))
         {
              count = count + 1; //counts the number of times the loop is run
              numbers[j] = numbers[j-1];
              j = j - 1;
         }
     numbers[j] = key;
     cout >> array; //prints out the new sorted array to the screen
     
     }
}

line 16: That will statically allocate the array based on some random value of SIZE because SIZE was not initialized to anything. What you want is a pointer

int SIZE = 0;
int* array = 0;

lines 32 to 57 is not needed. You can easily get the file size after opening the file, seek to the end of the file, call tellg() and tellg() will give you the file size in bytes. Divide that by sizeof(int) and you have the answer you want.

Now after setting variable SIZE as above you have to allocate memory for the array.

size = new int[SIZE];

lines 60-64 are wrong because eof() doesn't work that way, and because it doesn't write to the array correctly. getline() works with strings, not integers, although you can read integers as strings but then you have to convert the string to an int.

int count = 0;
while(count < SIZE &&  infile >> array[count] )
  count++;

I kinda knew lines 32 - 57 were not the best way of setting the size of the array. I have looked up the functions you have recommended (seek and tellg) but am not sure how they will help. Each file will have a number of intergers, between 8 to 16284 corresponding to the number in the file name (Num8.txt, Num128.txt, etc). How will getting the file size in bytes help? What am I missing?

It won't help if it is a text file. I was assuming it was a binary file, which I don't think you have.

I think what you might want to do is set SIZE to the maximum size you will need. If you don't need them all then no harm done. Then you don't need lines 32-57 at all.

const int SIZE = 16284;
int array[SIZE] = {0}; //array sized for each file input and initialize all elements to 0

Check limits.h to see if an int on your system can hold that large a number. If not then you should probably use a long, if sizeof(long) is not the same as sizeof(int)

Ok, here is what I have now. I am still getting errors when it comes to calling the function and passing the values.

#include <cstdlib>
#include <iostream>
#include <math.h>
#include <fstream>
#include <iomanip>
#include <sstream>

using namespace std;


void insertion_sort(int numbers[], int* array[16284]);

int main()
{
    const int SIZE = 16284;
    int array[SIZE] = {0}; //array sized for each file input
    int numbers;
    int count = 0;     
    ifstream infile; //input data file
    ifstream fin;    // file data opject
    char filename[50];
        
    cout << "Enter the name of the file you wish to open. "<<endl;
    cin >> filename;
    fin.open(filename);
    
    if(infile.bad()) //checks to see if the file will open
    {
      std::cerr <<"Error. Could not open the datafile "<< filename  <<endl;
      exit(8);
    }
    else
    { 
       while(count <= SIZE && infile >> array[count]) // the contents of the file are read into the array until the end of file is reached
       {
        count++;
        insertion_sort(numbers, array[]); //insertion sort function is called
       }
    }
    
    fin.close();
    system("PAUSE");
    return EXIT_SUCCESS;
}

void insertion_sort(int numbers[], int* array[])
{
     int i;
     int j;
     int key;
     //int SIZE;
     int count = 0;
     for (i=1; i < array; i++)
     {
         key = numbers[i];
         j = i;
         while((j > 0) && (numbers[j-i] > key))
         {
              count = count + 1; //counts the number of times the loop is run
              cout <<"The number of times insertion sort loops is "<< count <<endl;
              numbers[j] = numbers[j-1];
              j = j - 1;
         }
     numbers[j] = key;
     cout >> array[]; //prints out the new sorted array to the screen
     
     }
}

Ok, here is what I have now. I am still getting errors when it comes to calling the function and passing the values.

Such as? :icon_rolleyes:

Psychically debugging code is hit or miss proposition. Mostly miss. Unless you give us information, there's not much we can do...

Sorry about that. I thought I had copied and pasted the error messages

line 37: expected primary-expression before ']' token. In function `void insertion_sort(int*, int**)':

line 53: ISO C++ forbids comparison between pointer and integer

line 65: expected primary-expression before ']' token

I am assuming these errors have something to do with the way I have used my pointers and function call.

Personal suggestion, and this might be way out there, but I would look into the Standard Template Library and Vectors ^_^

Maybe I am way off base and you have to do it the way you are attempting but a

vector.push_back()
and std:: Sort

might do the trick :)

Cameron

line 37: delete the brackets [] after array. You don't normally use those in a parameter unless you put a number inside.

line 53: i is an integer, array is a pointer -- you can't compare them. i < array is wrong.

line 65:If you want to display the array values you have to do it one element at a time in a loop.

line 37: delete the brackets [] after array. You don't normally use those in a parameter unless you put a number inside.

line 53: i is an integer, array is a pointer -- you can't compare them. i < array is wrong.

line 65:If you want to display the array values you have to do it one element at a time in a loop.

I think I have fixed line 65 with the following code

for (int p = 0; p < 16284; p++) //prints out the sorted array 
     cout << array[p] << endl;

I am still working on lines 53 and 37 as I still get the same error messages even after the suggested changes.

The problem with that insertion sort function is the the function doesn't know how many elements are in those two arrays -- could be as few as 1 or as many as can be held in an integer, which is a several million. Put a number inside those brackets so that the function will know how big those arrays are. I'm using an arbritrary number here so you would use the correct number. void insertion_sort(int numbers[255], int* array[255])

After speaking with my professor, we realized the insertion sort algorithm on the handout was not the one we were to use. The correct call should have been..

void insertion_sort(int numbers[], int array_size)

The function only has one array. The array_size is equal to the total numbers of integers in the data file. Data file "Num8.txt" will have 8 integers, "Num16.txt", will have 16 integers, and so on. Each file will have 2 * n integers. I have rewritten the code some as well.

#include <cstdlib>
#include <iostream>
#include <math.h>
#include <fstream>
#include <iomanip>
#include <sstream>

using namespace std;


void insertion_sort(int numbers[], int array_size);

int main()
{
    int array_size = 16284; //array sized for each file input
    int count = 0;
    int numbers[count];
    ifstream infile; //input data file
    ifstream fin;    // file data opject
    char filename[50];
        
    cout << "Enter the name of the file you wish to open. "<<endl;
    cin >> filename;
    fin.open(filename);
    
    if(infile.bad()) //checks to see if the file will open
    {
      std::cerr <<"Error. Could not open the datafile "<< filename  <<endl;
      exit(8);
    }
    else
    { 
       while(count <= array_size && infile >> numbers[count]) // the contents of the file are read into the numbers array until the end of file is reached
       {
        count++;
       }
    }
    insertion_sort(numbers, array_size);
    system("PAUSE");
    return EXIT_SUCCESS;
}

void insertion_sort(int numbers[], int array_size)
{
     int i; 
     int j;
     int key;
     int count = 0;
     //int array;
     for (i=1; i < array_size; i++)
     {
         key = numbers[i];
         j = i;
         while((j > 0) && (numbers[j-i] > key))
         {
              count = count + 1; //counts the number of times the loop is run
              cout <<"The number of times insertion sort loops is "<< count <<endl;
              numbers[j] = numbers[j-1];
              j = j - 1;
         }
     }
     numbers[j] = key;
     
     for(int p = 0; p < 16284; p++) //prints out the new sorted array to the screen  
        cout << numbers[p] << endl;  
}

I have just gotten it to compile but am working on the results now. No, it doesnt work correctly but it will.

I have streamlined my program some and it works better but I now have two new problems. First the code.

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;



void insertionSort(long numbers[], long array_size);

int main()
{
  long values;
  long i;
  long count = 0; //counts the number of numbers in the input file
  long items = 0;
  long numbers[count];
  ifstream in_file;  //input file
  char filename[50];
  
  cout<<"Please enter the name of the data file you wish to open " <<endl;
  cin >> filename;
  
  in_file.open(filename); //opens the file the user typed in
  
  if(!in_file.is_open()) //checks to see if the file opens or not
     {
       cout<<"Could not open the file  " << filename <<endl
           <<"Program in now closing. \n";
           exit(EXIT_FAILURE);
     }
  
 
  in_file >> values; //gets first value from input file
  cout<< "the first value is "<< values <<endl; //this is just a test to check if the above statement is correct
  while(in_file.good())
  {
      ++count;
      in_file >> values;
  }
  
  items = count;//count of total numbers in the file
    
  for (i = 0; i < values; i++)
    numbers[i] = values;
  
  insertionSort(numbers, items); //call to insertion sort function

  for (i = 0; i < items; i++)
    cout<< numbers[i]<<endl;
  
  in_file.close();
    
  system("pause");
}


void insertionSort(long numbers[], long array_size)
{
  long i, j, key;
  long counter; 
  for (i=1; i < array_size; i++)
  {
    key = numbers[i];
    j = i;
    while ((j > 0) && (numbers[j-1] > key))
    {
      counter = counter + 1; //counts the number of times to sort function loops
      numbers[j] = numbers[j-1];
      j = j - 1;
    }
    numbers[j] = key;
  }
  cout<< "The cost of the function is " << counter <<endl;
}

Problem 1, (lines 37 -43). The program will correctly count the number of integers in the .txt file and will create the correct size array. But it will not list the actual numbers from the file. For example, input file "num8.txt" has 8 integers from 1-8. So an array of length 8 will have 8 integers in various order. How would I get each integer to sort it? I thought of using the following code...

while(in_file.good())
{
    for(i=0, 1<values, i++)
        in_file >> values[i]; //gets first value from input file
 }

The problem with this is, it creates another array and the function call already uses values to set the array size for

int numbers[]

Problem 2: When compiled the output will all be sorted correctly on any file with 64 integers or less. The program crashes with files that have larger numbers of integers. I can not understand why I would run out of memory as I have declared all int values as longs.

Now for sleep. :)

You have to change the initialization of numbers

long count = 0; //counts the number of numbers in the input file
  long items = 0;
  long numbers[count];

Problem 1, (lines 37 -43). The program will correctly count the number of integers in the .txt file and will create the correct size array. But it will not list the actual numbers from the file. For example, input file "num8.txt" has 8 integers from 1-8. So an array of length 8 will have 8 integers in various order. How would I get each integer to sort it? I thought of using the following code...

In the while loop you need to load the value just read into the array. What you are doing is reading all the values in the while, then loading the last value read into the array with the for loop.

Problem 2: When compiled the output will all be sorted correctly on any file with 64 integers or less. The program crashes with files that have larger numbers of integers. I can not understand why I would run out of memory as I have declared all int values as longs.

The size of your variables have nothing to do with the number of values in an array.

You've declared

int main()
{
  long count = 0; //counts the number of numbers in the input file
  long numbers[count];

You just declared numbers to be an array of 0 values. Are you getting a warning or error on the long numbers[count]; statement?

I tried to compile this code with another compiler(Visual C Express Edition) and it did give an error message about the array not have a value. So far the only problem is just reading the integer data from the file and putting it in the array. I currently have the program reading the file's data like so...

while(in_file.good())
  {
    ++count;
    for (i = 0; i < values; i++) //this for loop was origionally under items=count
    {
        in_file >> values;
        numbers[i] = values;
    }
  }

Shouldn't values be an array as well to read the data? Or is the program taking each value read, putting it into numbers, and then getting the next value?

That loop is just crazy. How can that loop ever execute correctly if the value of values is read from a file. You need a completly different variable when inputting the file

int i = 0;
while( in_file >> numbers[i] )
 {
      ++i;
 }

Did you fix numbers?

Since you changed your code, you might want to share it with us.

I did manage to fix the code. It is not the best programming job but I'm proud since its my first program in years. In the code, I ask the user for the input file and to enter a number to set the size of the array. The largest array needed for any sort will be 16384. I did not set the array size to max as I did not know how an array that is larger than the input would affect the sort. I did learn that I have to work on understanding functions, arrays, and pointers. I would like to thank everyone that struggled with me on this program.

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;



void insertionSort(int numbers[], int array_size);
int counter; //counts the cost of the sort

int main()
{
  int i;
  int n;
  int size;
  
  cout <<"Enter the number of integers in the file and the size of the array. "
  <<endl<<endl; 
  cout <<"The number will be the same as the number in the file name. "<<endl
  <<endl;
  cout <<"If enter the wrong number the program will crash. "<<endl;
  
  cin >> n; //number of integers in the file
  size = n; //size of the array
    
  int numbers[n]; //the integers in the input file
  ifstream in_file;  //input file
  char filename[50];
  ofstream out_file; //output file
  char o_filename[50];
  
  cout<<"Please enter the name of the data file you wish to open. " <<endl;
  cin >> filename;
  
  cout<<"Enter the name of the file you wish to save the output to. "<<endl;
  cin >> o_filename;
  
  in_file.open(filename); //opens the file the user typed in
  out_file.open(o_filename); //opens the output file
  
  if(!in_file.is_open()) //checks to see if the file opens or not
     {
       cout<<"Could not open the file.  " << filename <<endl
           <<"Program in now closing. \n";
           exit(EXIT_FAILURE);
     }
  
  
  while(in_file.good()) //puts integers from the input file into the array
  {
    for (i = 0; i <= n; i++) 
    {
        in_file >> numbers[i]; 
    }
  }
    
  insertionSort(numbers, size); //call to insertion sort function

 
    for (i = 0; i < size; i++)
    {
       cout << numbers[i]<<endl;
       out_file << numbers[i]<<endl;
    }
       
    in_file.close();
    out_file.close();
  
  system("PAUSE");
}


void insertionSort(int numbers[], int array_size)
{
  int i, j, key;
  int counter; //counts the number of times to sort function is called
  for (i=1; i < array_size; i++)
  {
    key = numbers[i];
    j = i;
    while ((j > 0) && (numbers[j-1] > key))
    {
      counter = counter + 1;
      numbers[j] = numbers[j-1];
      j = j - 1;
    }
    numbers[j] = key;
  }
  
  cout<< "The cost of the function is " << counter <<endl;  //prints out how many times the loop in the sort was called.
  
}
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.