Professional Documents
Culture Documents
Structures and ENUM
Structures and ENUM
Structures and ENUM
Defining structure
// englarea.cpp
// demonstrates nested structures
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct Distance //English distance
{
int feet;
float inches;
};
////////////////////////////////////////////////////////////////
struct Room //rectangular area
{
Distance length; //length of rectangle
Distance width; //width of rectangle
};
////////////////////////////////////////////////////////////////
int main()
{
Room dining; //define a room
dining.length.feet = 13; //assign values to room
dining.length.inches = 6.5;
dining.width.feet = 10;
dining.width.inches = 0.0;
//convert length & width
float l = dining.length.feet + dining.length.inches/12;
float w = dining.width.feet + dining.width.inches/12;
//find area and display it
cout << Dining room area is << l * w
<< square feet\n ;
return 0;
}
Days of a week
enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
Enumerations are treated internally as integers. This explains why you can perform
arithmetic
and relational operations on them. Ordinarily the first name in the list is given the value 0,
the
next name is given the value 1, and so on
specifying integet vaue to enum - enum Suit { clubs=1, diamonds, hearts, spades };
Abstract data type
Strings
Two typoes csting array of charecters - char* strings(char str[MAX];), anf other string
String constants - char str[] = Farewell! thou art too dear for my possessing.;
#include <iostream>
using namespace std;
int main()
{
const int MAX = 80; //max characters in string
char str[MAX]; //string variable str
cout << \nEnter a string: ;
cin.get(str, MAX); //put string in str
cout << You entered: << str << endl;
return 0;
}
Copying string in hard way - for(int j=0; j<strlen(str1); j++) //copy strlen characters
str2[j] = str1[j];
Array of strings
//sstrass.cpp
//defining and assigning string objects
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1(Man); //initialize
string s2 = Beast; //initialize
string s3;
s3 = s1; //assign
cout << s3 = << s3 << endl;
s3 = Neither + s1 + nor ; //concatenate
s3 += s2; //concatenate
cout << s3 = << s3 << endl;
s1.swap(s2); //swap s1 and s2
cout << s1 << nor << s2 << endl;
return 0;
}
Getline to read string handles blanks and multiple lines - getline(cin, address, $);
Pointers
& - get address
* - print value
Every byte in the computers memory has an address. Addresses are numbers, just as they
are for houses on a street.