🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

C++ Workshop - Arrays & Strings (Ch. 13)

Started by
35 comments, last by alphastickmania 15 years, 1 month ago
Arrays I have been familiar with for quite some time, I only wish strings were as easy in C++ as they were in QuickBASIC.

Chapter 13 Quiz

1. What is an array?
A variable, which holds several different values.

2. How do you access an element in an array?
SomeArray[2] will return the third element of SomeArray.

3. Are offsets (indexes) numbered starting from 0 or from 1?
0

4. What happens if you write to an index that is outside the range of your array?
The program could possibly crash.

5. What are fence post errors?
When the numbering is off. A 10-foot fence with a post for every foot would have 11 posts not 10, and if you say 10 the numbering is off, which is a fence post error.

6. How do you initialize arrays with simple data types?
int SomeArray[5] = { 1,2,3,4,5 };

7. If you initialize an array with values, are you required to specify the size? Should you?
No, however it's recommended that you do.
8. When using an array of objects, which constructor gets called when the array is created?

9. Is it possible to have multi-dimensional arrays?
Yes

10. Is there a maximum number of dimensions which are supported by C++?
There is not a maximum, though having too many can add up and consume a lot of memory.

11. In C++, what is another way of thinking about an array name, as it pertains to pointers?
It's a constant pointer to the first element of the array.

12. Is it legal to use array names as replacements for the construct in question? How about vice-versa?
Yes, and vice-versa.


13. What happens if you allocate a dynamic array of memory and don’t delete it, including the [] operator?
A memory leak will be made.

14. Can you set the size of an array created on the stack at run-time?
Nope

15. Can you set the size of an array created on the heap at run-time?
Yea
--Dbproguy - My Blog - Tips, Opinions and Reviews about C++, Video Games, and Life
Advertisement
does anyone have an answer for this cause its been bugging me for some time
why is it that when a call the sizeof operator on the name of an array without the [] it returns the size of the entire array. I mean if the name of the array without the [] operator is a pointer to the first element in the array how come it does not just return the size of the pointer?
Quote: if the name of the array without the [] operator is a pointer to the first element in the array
Repeat after me, "an array is not a pointer", 100 times. If your book equates the two, it has oversimplified, to the point that the devil in the details has snared you. The array-pointer relationship is tricky, so don't feel bad about having difficulty understanding it.

You may find the C-FAQ entry relevant. A number of entries concern the array pointer relationship actually.

If the C-FAQ looks like gibberish to you, or you aren't still clear on why sizeof works the way it does with arrays, make a post in the beginner's forum on it.
Sort of stuck here. Was wondering for any help? Reading Files and storing them in arrays for modifications.


Quote:

00001,Telephone Jacks,10.75,15.00
00002,Phone Starter Kit,5.25,7.50
00003,Home base module,1.00,2.50
4,Boring School Textbook,2,5
5,Exciting School Textbook,6,7
06,Really Great Examination Answers,5.1,15.4
07,True Examination Answers,1.35,9.99
08,Home Grown Term Paper,1.25,10.75
54,Z-Top Cook Stove,12.50,107.50


Reading files is much easier in C. What i wanted to do is read the file byte by byte. I dont think i can do this in C++ so im forced to "stream it up".


i dont need to print anything to the file so im using ifstream inFile;
Dynamic Allocation is not an issue for me, but after this is solved i would like to learn :)

#include <iostream>#include <fstream>#include <string>struct products{       int pID;       char desc[256];       float cost,       price,       markup;}products;using namespace std;int main(int argc, char** argv[]){    int myNum,    numArray[35],    lineCount,    prodCount,    numPtr,    strPtr,    numIdx,        *digPtr;        char myStr[1024],    digits[255],    myDec[1024],    myDec2[1024],    myChar;        string myFile, mylines;     ifstream inFile;        struct products myProd[1024];        cout << "Please enter Filename: ";    cin >> myFile;            // forcing user to enter a valid file name               inFile.open(myFile.c_str(), ios::in); //open file for reading        if (!inFile)    // validating the file    {         cout << myFile << " is not on Disk!";         return 1;        // program closes cuz no file    }        inFile.get(myChar);  // read a char from file    inFile.getline(myStr, 1024);    while ( !inFile.eof() && !inFile.fail() )  // iterate if not fail or EOF    {            // mychar = ?                 if (myStr[myChar] == ',')break;                //cout << myChar;                // display character(s)        inFile.get(myChar);     }           cout << myStr;        inFile.close();          // not done tho :p                      system("pause");    return 0;}


What im trying to do at this point is to loop through the file using an integer varaible. Breaking to the next line after each comma. Then store what i've read in an array and finally converting each number to a single digit.









#include <iostream>

using namespace std;

int main()

//Function to initialize an int array to 0.
//The array to be initialized and its size are passed
//as parameters. The parameter listSize specifies the
//number of elements to be initialized.

void initializeArray(int list[], int listSize)
{
int index;

for (index = 0; index < listSize; index++)
list[index]= 0;
}

//Function to read and store the data into an int array.
//The array to store the data dn its zie are passed as
//parameters. The parameters listSize specifies the number
//of elements to be read.
void fillArray(int list[], int listSize)
{
int index;

for (index = 0; index < listSize; index++)
cin >> list[index];

}

//Function to print the elements of an int array.
//The array to be printed and the number of elements
//are passed as parameters. The parameter listSize
//specifies the number of elements to be printed.

void printArray(const int list[], int listSize)
{
int index;

for (index = 0; index < listSize; index++)
cout << list[index] << " ";
}

//Function to find and return the sum of the
//elements of an int array. The parameter listSize
//specifies the number of elements to be added.
int sumArray(const int list[], int listSize)
{


int index;
int sum = 0;

for (index = 0; index < listSize; index++)
sum = sum + list[index];

return sum;
}


//Function to find and return the index of the first
//largest element in an int array. The parameter listSize
//specifies the number of elements in the array.

int indexLargestElement(const int list[], int listSize)
{
int index;
int maxIndex=0; //assume the first element is the largest

for (index = 1; index < listSize; index++)
if (list[maxIndex] < list [index])
maxIndex = index;

return maxIndex;
}

//Function to copy one array into another array.
//The elements of listOne are copied into listTwo.
//The array listTwo must be at least as large as the
//number of elements to be copied. The parameter
//listOneSize specifies the number of elements of
//listOne to be copied into listTwo.

void copyArray(const int listOne[], int listTwo[],
int listOneSize)
{

int index;

for (index = 0; index < listOneSize; index++)
listTwo[index] = listOne[index];


}


I got this error ->>>>>


error C2144: syntax error : 'void' should be preceded by ';'

Can somebody tell me what I did wrong?


You have "int main()" floating by itself at the top. If you were to follow that with a semicolon, that would be a declaration of main (which is unnecessary, because it is illegal to explicitly call main() in C++).

You should probably provide a definition of main() towards the end of your program. You could even provide some tests to make sure your functions work.

The last thing I would say is a stylistic note. Declare iteration variables as part of a for loop. Most programmers keep these variable names short, e.g. "i" or "j".
for(int i = 0 ; i < someValue ; ++i){    // body of loop...}


Quote: Original post by rip-off
You have "int main()" floating by itself at the top. If you were to follow that with a semicolon, that would be a declaration of main (which is unnecessary, because it is illegal to explicitly call main() in C++).

You should probably provide a definition of main() towards the end of your program. You could even provide some tests to make sure your functions work.


Umm... okay. Actually, if you are just starting to learn C++ and cannot "tango" with it yet, then always place your main() below all your other code.

However, if you get better in coding, you might want to declare function prototypes instead, which is a "somewhat" advanced stuff for beginners. But if you do that, your main can be anywhere you want as long as it's under those prototypes and the code will still work.

This topic is closed to new replies.

Advertisement