we just started a new topic in class of arrays, he gave us an explanation and it was very foggy, but now i got home to do my program i can not even figure out what is going on. Any help you can give would be great.

The program we had to write is as follows:

Write a program that will read in an unknown number(not more than 40) of dates from a text file in the form mm/dd/yyyy. In orger to sort them chronologically, the program must convert the date into the form yyyymmdd. After sorting, reconvert the date back to its original format and display the list of dates in sorted order from old to recent.

This is what I have so far of my somewhat understanding of the lecture, as you can tell I am very confused;

int main()
{
    time_t t;
    time(&t);

    yl;
    cls;

    int count = 0;
    string date [40];
    int number [50];  
    int j, i;

    for (i=0; i<40; i++)
        {
        date [i] = "";
        number [i] = 0;
        }


if (!infile)

    {
       cout << "An error has occurred while opening file" << endl;
       print << "An error has occurred while opening file" << endl;
       exit (1);
    } 

    while (!infile.eof())
          {      
          infile >> date [i];
          for (i=0; i<40; i++)                 

          cout << date << endl;     
          }
}

I am very confused with what is going on and I want to know the understanding and explanation to what is going on within this program and the understanding behind arrays.

Any help with the program and places where I can read or just a good brief explanation to what is going on in arrays, and how I can understand how to write this program.

Thank You very much for your assistance

Recommended Answers

All 17 Replies

Member Avatar for iamthwee

>In orger to sort them chronologically, the program must convert the date into the form yyyymmdd.

I think you've got two options here. One, yyyymmdd when stored as a string will be able to sort chronologically by itself or two, you have to separate yyyy mm dd into three parts each one represented as an integer and do a sort according to this.

I suspect it is likely to be option one seeing as it appears the easiest.

>while (!infile.eof())
This should be avoided because of a notorious bug, instead use the following which is considered the defacto when reading in lines:-

string line;
ifstream read ("c:\\...path_to_file");
while ( getline( read, line, '\n') )
{
 //do stuff with lines
}
read.close();

>string date [40];
The trouble here is if your file contains more than 40 dates it will overflow. Therefore -and for the sake of brevity it may be wise to declare a sufficiently large number as the initialiser.

string date[1000];

Write a program that will read in an unknown number(not more than 40) of dates from a text file in the form mm/dd/yyyy. In orger to sort them chronologically, the program must convert the date into the form yyyymmdd. After sorting, reconvert the date back to its original format and display the list of dates in sorted order from old to recent.

Something like this:

  • Open the file for reading, and if error occurs, exit the program
  • Read from the file, one line at a time by the method given by Iamthwee.
  • Parse out the individual parts like month, day and year from the line just read. Create a new string from the parts read, something like "yyyymmdd".
  • Convert the given string to long using string streams.
  • Perform this procedure for each line and store each entry is an array of long.
  • Sort this set of numbers in ascending order.
  • Read the sorted array of longs and perform the reverse process.

This is as simple as it gets, though is not a very generic and efficient implementation, it should help you get started.

>> understanding behind arrays

Without knowing what you know already this may be difficult, but here's a general presentation.

Arrays are variables that can hold the information about a group of objects in contiguous memory. You can use an array almost like any other object. For example you can refer to it by it's name. You can pass it to functions. If the type of the array includes the keyword const, then the information in the array cannot be changed after initialization. Arrays can be declared using static or dynamic memory (if you don't know about the difference between static and dynamic memory yet, you will learn about later). And so on. One big difference to other categories of variables, however, is that you cannot assign one array to another.

Each ojbect that has information stored in the array must be of the same type. The information about a given object stored in the array is frequently callled an element of the array.

The type of objects that can have information stored in the array must be known at compile time and, if the array is going to be declared using static memory, which is what you'll be doing now, then the maximum number of objects that could be stored in the array must be known at compile time, too. So,

int a1[10];

is the declaration of an array of 10 objects of type int and

const int NUM = 8;
Car a2[NUM];

a2 is an array of 8 Cars. Note than both 10 and NUM are of type const int. That is a requirement for declaring arrays using static memory.

You can access the information about each object in an array by using the [] operator. The sytnax is like this:

a1[x];

x is frequently called the index of the object (information) and it must resolve to an int. x ranges from zero to one less than the maximum number of objects in a1. Using x with the value of maximum number of ojects in a1 or beyond is a frequent source of errors. So for example, in a1 above the index could be from 0-9 and in a2 the index coud be 0-7. To extend this further the first element in a2 can be accessed using the following notation:

a2[0];

and the third element in a2 can be accessed using the following notation

a2[2];

If elements in the array aren't intialized or assigned a value before you try to use them, then they will be of undetermined value, that is junk. Each element of the array may be initialized to the same value using an initialization statement like this:

int a1[10] = {0};

This means that all 10 elements of a1 will be initialized with the value of zero. Alternatively, each element in an array may be initialized to a different value:

int a1[4] = {99, 5, -27, 555};

means that the a1[0] is initialized to 99, a1[1] is initialized to 5, a1[2] is initialized to -27, a1[2] is initialized to 555.

In addition, as long as the type of the array isn't constant, each element in the array can be assigned any valid value desired.

for(int i; i < 10; ++i)
a1 = i;

means that each element of a1 will be assigned the value of it's index.

Each element in the array can be used just like an object of that type. So this:

int a1[3] = {0};
int num = a1[1];
cout << num;

will print the value of 0 to the screen.

The name of the array can be used as the address of the first element in the array. Thus

int a1[10] = {4};
int * num = &a1[0];
int * num1 = a1;
cout << *num << " + " << *num1 << endl;

will print 4 + 4 to the screen.

Arrays can be passed to functions. Thus, if you have a function whose prototype looks like this:

void func(int []);

then you could pass it an array of type int like this:

func(a1);

One confusing tidbit is that this will also work:

void func2(int *)

func2(a1);

as long as a1 is the name of an array of type int.

Arrays are passed to functions by reference automatically. So if you don't want the function to change any information in the array it is passed you should make it a const type.

Because an array name can be used like a pointer in many circumstances some people mistakenly believe it is a pointer, but it's not.

You should also know that in C++ there is a special type of an array called a null terminated char array and there are special rules for handling null terminated char arrays. The importance of null terminated char arrays is that all strings are based on null terminated char arrays. But that's a discussion probably best kept for later, too.

Another topic concerning arrays is that they aren't limited to a single "dimension". That is, an array can be an array of other arrays. But don't worry, you'll learn about multidimensional arrays later, too.

without booring you too much or reapeating valuable information already posted i will tell you how i began to understand arrays.

when i first started programming i had no idea what they were or how they worked untill i started thinking about them like this

Boxes.

as simple as that

so when someone said i had an int array that was 6 in size i would simply allocate six boxes in my head


[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

just like that. I would even draw it on paper and test my statements by doing them by hand and drawing lines between the boxes.

it helped me tons to see how one could manipulate the data within them and how they can be a powerful resource if used correctly.

Thank Everyone for the description and explanation behind arrays. They seemed very confusing to me when I first learned them but now I am starting to begin to understand them much better. I wanted to know if you can post some more examples and explanations to make sure I fully grasp the concept.

As far as my program goes I followed what one of the posts said, and wanted to know if someone can take a look I have it doing everything I need it reads in the dates, removes the / between mm/dd/yyyy, but now I am trying to change to yyyymmdd. So it can be sorted. I am pretty sure I need to use a swap( , ) function. I also am not sure what exactly is going on. I dont know how to swap, and not sure how to sort them cronologically, then I have to transfer back to mm/dd/yyyy but stay in new order and then output. << thats where my problems lie

This is what I have so far:

int main()
{
    time_t t;
    time(&t);

    yl;
    cls;

    string date [40];  //1
    int number;    //1
    int j, i;          //1

    for (i=0; i<40; i++)       //1
        {
        date [i] = "";             //1
        number = 0;             //1
        }


if (!infile)

    {
       cout << "An error has occurred while opening file" << endl;
       exit (1);
    } 



  string dates;  //[B]2//not sure, is this reading in as a normal string.[/B]
  int a,b,c;
  ifstream read ("f:\\datelist.txt");   //2
  while ( getline( read, dates, '\n') )    //2
  {
        dates.erase (2,1);
        dates.erase (4,1);
        a = (0,2);
        b = (2,2);
        c = (4,4);
        swap (c,a);
  cout << dates << endl;
  }

  read.close();

Can you show me step by step, i see next to 1 i am intitializing the strings and seting them with and itital value and basically reserving that place in memory. Next to 2 am I am pulling the information from the file into the storage and placing it into the string date. But where the bold writing is, am I placing it into the memory I set aside in part 1, or is there a certain way to get it setaside in that memory section.

Sorry for all of the questions but I really am trying my best to understand and I appreciate all the help.

Member Avatar for iamthwee

Let's you you have split the date into three parts:

string one = "01";
string two = "04";
string three = "2007";

To create a new string just do:-

string date = three + two + one;

simple! I'll let you carry on. Sorting is your next priority. Look at bubble sort, perhaps?

Here's what I'd do to improve your code using tools already provided to you and to point you where to go from here

int main()
{
  string dates [40]; //to hold dates as strings 
  int number = 0; //to keep track of how many dates there are in the file

  //holding strings
  string day;
  string month;
  string year;
  string temp;

  //open file 
  ifstream read ("f:\\datelist.txt"); 

  /if file didn't open
  if(!read)
  {
    cout << "An error has occurred while opening  file" << endl;
    exit (1);
  } 

  //assume file is one date per line
  //each time through loop parse out day using getline()
  while ( getline( read, day, '/') ) 
  {
       //then parse out month and year
       getline( read, month, '/');
       getline(read, year);

       //combine the parsed parts into temp string
       temp = year + month + day;

       //add temp string to apporpriate index of arrray of dates
       dates[number++] = temp;
       
       //reset holding strings to be empty
      //probably don't have to, but I think it's good style.
      day = month = year = temp = "";
  }

  read.close();
  
  //sort the array called dates using the sort() function from STL or a bubble sort protocol or whatever else you wish.  Given the STL string class has comparison operators built in you shouldn't have to convert to int, just sort the strings however you'd like.

  //loop through dates after being sorted
      //change each date back to desired form
      //print date to screen as converted

  return 0;
}
commented: very clean code :) +5

OK, I've got question!
If the program is sorting external files, why define
time_t t and time(&t)?

I don't see them used in the program.

I have been working on this program and seem to be getting a handle on it. And have it set up ready to have a bubble sort performed at the word sort = but performing the actual sort is giving me some trouble, I am not understanding what is happening in each step of the sort. I put down some things that I got from my partial understanding of the book and some notes but not seeming to be right. I was wondering if someone could help me and also comment next to responce what each step of the sort does and how I can understand it.

So far I have:

string date [40];
    int number;
    int j, i, s=0, count;
    stringstream sshours;

    for (count=0; count<40; count++)
        {
        date [count] = "";
        number = 0;
        }


if (!infile)

    {
       cout << "An error has occurred while opening file" << endl;
       exit (1);
    } 



  string dates, sort, sorted;
  string first, second, third;

  ifstream read ("f:\\datelist.txt");
  while ( getline( read, dates, '\n') )
  {
        dates.erase (2,1);
        dates.erase (4,1);

        first = dates.substr(0,2);
        second = dates.substr(2,2);
        third = dates.substr(4,4);

        sort = third + first + second;  // [I]here I have the right form for sorting with the dates setup as yyyymmdd[/I] 

        for (i=0; i<count - 1; i++)
            for(j=i+1; j<count; j++)
                 if (sort [s] < sort [j])
                       s = j;

        sorted = sort [s];      

      cout << sorted << endl;  

  }

  read.close();

After I am finished sorting them chronologically I have to output the responces back to the form mm/dd/yyyy, which I think I can do just the sorting was giving me trouble. But if you do have any pointers on how to put back to proper form mm/dd/yyyy for output I would greatly appreciate it.

Thanks, for the help
Radskate360

Member Avatar for iamthwee

Hi, the problem is you are not storing the dates in an array. And the sort can only take place after the closing brace of the while(getline...) statement. Do you want me to show you an example?

Member Avatar for iamthwee
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
 
using namespace std;
 
int main ( void )
{ 
 string date [40];
 int number;
 int j, i, s = 0, count;
 stringstream sshours;
 for ( count = 0; count < 40; count++ )
 {
    date [count] = "";
    number = 0;
 } 
 string dates, sort, sorted;
 string first, second, third;
 int counter = 0; //initialise counter
 
 ifstream read ( "f:\\datelist.txt" );
 while ( getline ( read, dates, '\n' ) )
 {
    dates.erase ( 2, 1 );
    dates.erase ( 4, 1 );
    first = dates.substr ( 0, 2 );
    second = dates.substr ( 2, 2 );
    third = dates.substr ( 4, 4 );
    sort = third + first + second; 
    date[counter] = sort; //store it!
 
    counter = counter + 1; //increment counter
    cout << sort << endl;
 }
 
 //here is where you sort it
 for ( int i = 0; i < counter; i++ )
 {
     for ( int j = 0; j < counter; j++ )
     {
 
     }
 }
 
 read.close();
 cin.get();
}

Here is the template you need to look at. I've highlighted the things in red that I've changed. I've left the sort part for you to fill in.

if you could show me an example I would appreciate it, that way I can see what is going on in each step, and can you put a small description next to each step you do.

Thanks,

Member Avatar for iamthwee

Please see my previous post, just before you posted. :)

Member Avatar for iamthwee

If you have lots of blank lines in your file you might also want to change

while (getline (read,dates,'\n'))

to

while ( read >> dates )

I put this for the sort, and its not seeming to work, but i seem to not be getting a good handle on this sort idea. After all of your other help I pretty much understand all of the rest pretty well, but this one is giving me a holdup.

if (sort [s] < sort [j])
                       s = j;
sorted = sort [s];   
      cout << sorted << endl;

or

if (sort[i]<sort[j]);

still very confused on this idea.

Also wanted to ask you about this part at the top.

string date [40];   //[I][B]here it seems this is setup as array.[/B][/I]
 int number;
 int j, i, s = 0, count;
 stringstream sshours;
 for ( count = 0; count < 40; count++ )
 {
    date [count] = "";   //[I][B]and this initalizes and holds space  for info[/B][/I]
    number = 0;
 } 
 string dates, sort, sorted;  //[I][B]but here is this reading in as part of array or dates looks like normal string here. What i'm trying to ask is does the string have to be read in a certain way, or does it look like a normal string, and how do u know it is being stored in the place we set aside in the beginning.[/B][/I]
 string first, second, third;
 int counter = 0; //initialise counter
 
 ifstream read ( "f:\\datelist.txt" );
 while ( getline ( read, dates, '\n' ) )
 {
    dates.erase ( 2, 1 );
    dates.erase ( 4, 1 );
    first = dates.substr ( 0, 2 );
    second = dates.substr ( 2, 2 );
    third = dates.substr ( 4, 4 );
    sort = third + first + second; 
    date[counter] = sort;
Member Avatar for iamthwee

If you don't understand sorting what I would recommend you do is create a separate program to test out your ideas.

Have a look below:-
http://mathbits.com/MathBits/CompSci/Arrays/Bubble.htm

Create a program with an array of ints and try to sort them.

#include <iostream>

using namespace std;

int main ( void )
{
  int array[]={9,4,6,5,7,8,3,2,1};
  cout << "Before sorting:";
  for ( int i = 0; i < 9; i ++ )
  {
    cout << array[i] << " ";
  }

  //sort it here
 //then print the sorted array
}

Try one more time, have a look at that link and if you are still stuck come back here...

To get the strings in desired printable form again, reuse the processes you just used:

Declare a string to represent a backslash.

Loop through the array of sorted strings and

1) Use the substr() function to break each string in the array back into three individual strings representing the day, month and year.

2) Then just and mix and match the various parts with a couple well placed backslashes to get the output you want.

until you're done.

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.