Wednesday, June 29, 2011

Character strings and Strings

#include <iostream>
#include <string> //adding the string library

using namespace std;

//function signature
void SimpleArray();
void CharacterArray();
void InputStrings();
void UsingStrings();

int main()
{
//comment or uncomment the one you want to test
//SimpleArray();
CharacterArray();
//InputStrings();
//UsingStrings();
char c;
cin >> c;
}

void SimpleArray()
{

//a basic array
const int SIZE=4; //only constants or literals can be used
int myArray[SIZE];
//assigning values
myArray[0]=23;
myArray[1]=16;
myArray[2]=29;
myArray[3]=30;

//a clumsy way to get the average
//the first part of the equation is cast to a double so
//that there can be decimals in the answer
cout << "The Average is " <<
(double)(myArray[0] + myArray[1] + myArray[2] + myArray[3])/SIZE << endl;

//another way of initializing an array
int myArray2[]={4,34,12,23,2};

//a way of calculating the length of a an array
int arraysize=sizeof(myArray2);
int intsize=sizeof(int);
int arraylength=arraysize/intsize;
cout<< arraysize <<" "<< intsize<<" " << arraylength << endl;


//outputing an element of an array
cout << myArray2[2] << endl;

}

void CharacterArray()
{
//in c character arrays are the way
//you do strings
//in C++ you can do character arrays
//or import the string library
//a literal way to construct a character array
//which you never have to do
//the '\0' is a termination character
char name[]={'S','t','e','v','e','\0'};

//an easier way to initialize a character array
char lastName[]="Conger";

//another character array
char office[]="My Office is in 3176";

//outputing the arrays. Notice, we can just use
//the array names and not have to specificy the particular index
//values
cout << name << " " << lastName << " " << office << endl;
//concating character array litterals
cout << "Steve " "Conger " "\n";
//outputing a single character
cout <<lastName[3] << endl;

//getting the length of a character array
cout << strlen(office) << endl;
}

void InputStrings()
{
//declaring an empty character array of 50 elements
char cityName[50];

cout << "Enter a city Name" << endl;
cin.getline(cityName, 50); //using cin.getline to get the whole line
//it requires the character array name and the size of the character array

cout << "the city you entered is " << cityName <<endl;
}

void UsingStrings()
{
//declare a string variable (using the string library)
string name, city;
cout << "Enter your name" << endl;
getline(cin, name);//a different form of getline using strings
cout << "Enter City " << endl;
getline(cin, city);

string output = name + ", " + city; //string concatination
cout << output << endl;

//getting the length of string
cout << " the length of city " << city.length() <<endl;






}

No comments:

Post a Comment