| | |
Hey Just started new topic with arrays, and having some trouble please help
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: May 2007
Posts: 37
Reputation:
Solved Threads: 0
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
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
>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,
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 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.
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 ddinto 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]; Last edited by iamthwee; Jun 24th, 2007 at 4:16 am.
*Voted best profile in the world*
•
•
•
•
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.
- 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.
I don't accept change; I don't deserve to live.
•
•
Join Date: Jul 2005
Posts: 1,671
Reputation:
Solved Threads: 261
>> 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] = 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 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] = 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.
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.
Dont forget to spread the reputation to those that deserve!
•
•
Join Date: May 2007
Posts: 37
Reputation:
Solved Threads: 0
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; //2//not sure, is this reading in as a normal string.
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.
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; //2//not sure, is this reading in as a normal string.
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.
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?
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?
*Voted best profile in the world*
•
•
Join Date: Jul 2005
Posts: 1,671
Reputation:
Solved Threads: 261
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
C++ Syntax (Toggle Plain Text)
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; }
•
•
Join Date: May 2007
Posts: 37
Reputation:
Solved Threads: 0
Re: Hey Just started new topic with arrays, and having some trouble please help
0
#10 Jun 26th, 2007
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; // here I have the right form for sorting with the dates setup as yyyymmdd
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
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; // here I have the right form for sorting with the dates setup as yyyymmdd
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
![]() |
Similar Threads
- is it bad (C++)
- yyy65 (Viruses, Spyware and other Nasties)
- Are you in it for the money? (Growing an Online Community)
- Deleting a pointer? (C++)
Other Threads in the C++ Forum
- Previous Thread: please answer
- Next Thread: 'Segmentation Fault'
| Thread Tools | Search this Thread |
api array based binary bitmap c++ c/c++ calculator char char* class classes code coding compile console conversion database delete deploy desktop developer directshow dll download dynamic dynamiccharacterarray email encryption error file forms fstream function functions game givemetehcodez google graph gui homeworkhelp iamthwee ifstream input int integer java lib linkedlist linker linux list loop looping loops map math matrix memory multiple news node number numbertoword output pointer problem program programming project python random read recursion recursive reference return rpg sorting string strings temperature template templates test text text-file tree unix url variable vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






