Vous êtes sur la page 1sur 22

ENGR 1200U Introduction to Programming Lecture 8 Simple C++ Programs (Chapter 2) (contd) Dr.

Eyhab Al-Masri

1992-2012 by Pearson Education, Inc. & John Wiley & Sons Some portions are adopted from C++ for Everyone by Horstmann

Strings

ENGR 1200U Winter 2013 - UOIT

Strings are sequences of characters: "Hello world"

If you include the string header, you can create variables to hold literal strings:

#include <string> using namespace std; ... string name = "Harry"; // literal string "Harry" stored

ENGR 1200U Winter 2013 - UOIT

String variables are guaranteed to be initialized even if you dont initialize them:

string response; // literal string "" stored

"" is called the empty or null string.

ENGR 1200U Winter 2013 - UOIT

Although we cant perform arithmetic on strings, the string data type provides a special string operation, called concatenation

uses the + operator the result of the concatenating (joining) two strings is a new string containing the characters from both strings
string bookTitle; string phrase1; string phrase2; phrase1="EngineeringProblemSolving"; phrase2= "withC++(ThirdEdition)"; bookTitle=phrase1+phrase2; EngineeringProblemSolvingwithC++ (ThirdEdition)

ENGR 1200U Winter 2013 - UOIT

Example

we could write

Concatenation works with named string constants, literal strings, and char data as well as string variables Example:
Restriction: at least one of the operands of the + operator must be a string variable or named constant
conststring WORD1="ngineering"; conststring WORD3="Solving"; conststring WORD5="C++(ThirdEdition)";

bookTitle=E +WORD1 +Problem+WORD3 + "with"+WORD5; EngineeringProblemSolvingwithC++(ThirdEdition)

ENGR 1200U Winter 2013 - UOIT

Example
string fname = "Harry"; string lname = "Morgan"; string name = fname + lname;

cout << name << endl; name = fname + " " + lname; cout << name << endl;

The output will be HarryMorgan Harry Morgan

ENGR 1200U Winter 2013 - UOIT

Concatenation of literal strings


string greeting = "Hello, " + " World!"; // will not compile

Literal strings cannot be concatenated


string greeting = H + e + l + l + o; // will not compile

at least one of the operands of the + operator must be a string variable or named constant

ENGR 1200U Winter 2013 - UOIT

Given the declarations


string firstName; string middleName; string lastName; string title; charmiddleInitial; charletter;

firstName="Michael";
lastName=;

middleName=firstName; middleName="";
"Edison"=lastName;

indicate whether the assignment statements are valid/invalid

lastName="Faraday";
letter=firstName;

title="Scientist";
middleInitial="A.";

middleInitial=''; letter=middleInitial;
firstName=Thomas;
ENGR 1200U Winter 2013 - UOIT

The length member function yields the number of characters in a string Unlike the sqrt or pow function, the length function is invoked with the dot notation:
int n = name.length();

ENGR 1200U Winter 2013 - UOIT

Once you have a string, you can extract substrings by using the substr member function. s.substr(start, length) returns a string that is made from the characters in the string s, starting at character start, and containing length characters. (start and length are integer values).

string greeting = "Hello, World!"; string sub = greeting.substr(0, 5); // sub contains "Hello"

ENGR 1200U Winter 2013 - UOIT

0?
string sub = greeting.substr(0, 5);

ENGR 1200U Winter 2013 - UOIT

string greeting = "Hello, World!"; string w = greeting.substr(7, 5); // w contains "World" (not the !) "World" is 5 characters long but why is 7 the position of the W in "World"?

0?
ENGR 1200U Winter 2013 - UOIT

H 0

e 1

l 2

l 3

o 4

, 5

W 7

o 8

r l d ! 9 10 11 12

In most computer languages, the starting position 0 means start at the beginning. The first position in a string is labeled 0, the second one 1, and so on. And dont forget to count the space character after the commabut the quotation marks are not stored.

ENGR 1200U Winter 2013 - UOIT

H 0

e 1

l 2

l 3

o 4

, 5

W 7

o 8

r l d ! 9 10 11 12

The position number of the last character is always one less than the length of the string The ! is at position 12 in "Hello, World!". The length of "Hello, World!" is 13. (C++ remembers to count the 0 as one of the positions when counting characters in strings.)

ENGR 1200U Winter 2013 - UOIT

H 0

e 1

l 2

l 3

o 4

, 5

W 7

o 8

r l d ! 9 10 11 12

string greeting = "Hello, World!"; string w = greeting.substr(7); // w contains "World!" If you do not specify how many characters to take, you get all the rest.

ENGR 1200U Winter 2013 - UOIT

H 0

e 1

l 2

l 3

o 4

, 5

W 7

o 8

r l d ! 9 10 11 12

string greeting = "Hello, World!"; string w = greeting.substr(); // w contains "Hello World!" If you omit the starting position and the length, you get all the characters (not much of substring!)

ENGR 1200U Winter 2013 - UOIT

ENGR 1200U Winter 2013 - UOIT

ENGR 1200U Winter 2013 - UOIT

Common Functions

1992-2012 by Pearson Education, Inc. & John Wiley & Sons Some portions are adopted from C++ for Everyone by Horstmann

10

fabs(x) sqrt(x) pow(x,y) ceil(x) floor(x) exp(x) log(x) log10(x)

computes absolute value of x computes square root of x, where x >=0 computes xy nearest integer larger than x nearest integer smaller than x computes ex computes ln x, where x >0 computes log10x, where x>0

ENGR 1200U Winter 2013 - UOIT

sin(x) cos(x) tan(x) asin(x)

sine of x, where x is in radians cosine of x, where x is in radians tangent of x, where x is in radians This function computes the arcsine, or inverse sine, of x, where x must be in the range [1, 1]. The function returns an angle in radians in the range [/2, /2]. This function computes the arccosine, or inverse cosine, of x, where x must be in the range [1, 1]. The function returns an angle in radians in the range [0, ]. This function computes the arctangent, or inverse tangent, of x. The function returns an angle in radians in the range [/2, /2]. This function computes the arctangent or inverse tangent of the value y/x. The function returns an angle in radians in the range [, ].

acos(x)

atan(x) atan2(y,x)

ENGR 1200U Winter 2013 - UOIT

11

isalpha(ch) isdigit(ch) isspace(ch) islower(ch) isupper(ch) tolower(ch) toupper(ch)

Returns true if ch is an upper or lower case letter. Returns true if ch is a decimal digit Returns true if ch is a whitespace character. Returns true if ch is an lower case letter. Returns true if ch is an upper case letter. Returns the lowercase version of ch if ch is an uppercase character, returns ch otherwise. Returns the uppercase version of ch if ch is a lowercase character, returns ch otherwise.

ENGR 1200U Winter 2013 - UOIT

Standard Input / Output

ENGR 1200U Winter 2013 - UOIT

12

cout is an ostream object, defined in the header file iostream cout is defined to stream data to standard output (i.e. the display) We use the output operator << with cout to output the value of an expression.
General Form:

cout << expression << expression;


Note: An expression is a C++ constant, identifier, formula, or function call.

ENGR 1200U Winter 2013 - UOIT

cin is an istream object defined in the header file

iostream
cin is defined to stream data from standard input (i.e.

the keyboard)

We use the input operator >> with cin to assign values

to variables

General Form

cin >> identifier >> identifier;

Note: Data entered from the keyboard must be compatible with the data type of the variable.

ENGR 1200U Winter 2013 - UOIT

13

The input operator >> skips all whitespace characters. The get() method gets the next character. Example:
int x; char ch; cin >> x >> ch; cin >> x; cin.get(ch);
Input stream: 45 c 39 b

Memory Snapshot x 45 x 39 ch c ch \n

ENGR 1200U Winter 2013 - UOIT

Sometimes the programmer does not know what should be stored in a variable but the user does. The programmer must get the input value from the user Users need to be prompted (how else would they know they need to type something?)

Prompts are done in output statements

The keyboard needs to be read from This is done with an input statement

ENGR 1200U Winter 2013 - UOIT

14

The input statement

To read values from the keyboard, you input them from an object called cin. The << operator denotes the send to command. cin >> bottles; is an input statement.

Of course, bottles must be defined earlier.

ENGR 1200U Winter 2013 - UOIT

Example: Read a string from the console: cout << "Please enter your name: "; string name; cin >> name; When a string is read with the >> operator, only one word is placed into the string variable. For example, suppose the user types

Harry Morgan
as the response to the prompt. This input consists of two words. Only the string "Harry" is placed into the variable name.

ENGR 1200U Winter 2013 - UOIT

15

You can read more than one value in a single input statement: Example1
cout << "Enter the number of bottles and cans: "; cin >> bottles >> cans; The user can supply both inputs on the same line: Enter the number of bottles and cans: 2 6

Example2 cout << "Please enter your name: "; string fname, lname; cin >> fname >> lname; gets Harry
ENGR 1200U Winter 2013 - UOIT

gets Morgan

ENGR 1200U Winter 2013 - UOIT

16

ENGR 1200U Winter 2013 - UOIT

When you print an amount in dollars and cents, you usually want it to be rounded to two significant digits. You learned how to actually round off and store a value but, for output, we want to round off only for display. A manipulator is something that is sent to cout to specify how values should be formatted. To use manipulators, you must include the iomanip header in your program: #include <iomanip> and using namespace std; is also needed

ENGR 1200U Winter 2013 - UOIT

17

Which do you think the user prefers to see on her/his gas bill? Price per liter: $1.22 or Price per liter: $1.21997

ENGR 1200U Winter 2013 - UOIT

endl places a newline character in the output buffer

and flushes the buffer.


setf() and unsetf()
Flag ios::showpoint ios::fixed ios::scientific Ios::setprecision(n) Ios::setw(n) ios::right ios::left Meaning

display the decimal point fixed decimal notation scientific notation set the number of significant digits to be printed to the integer value n set the minimum number of columns for printing the next value to the integer value n right justification left justification

ENGR 1200U Winter 2013 - UOIT

18

ENGR 1200U Winter 2013 - UOIT

ENGR 1200U Winter 2013 - UOIT

19

You can combine manipulators and values to be displayed into a single statement: price_per_liter = 1.21997; cout << fixed << setprecision(2) << "Price per liter: $" << price_per_liter << endl; This code produces this output: Price per liter: $1.22

ENGR 1200U Winter 2013 - UOIT

You use the setw manipulator to set the width of the next output field. The width is the total number of characters used for showing the value, including digits, the decimal point, and spaces. If you want columns of certain widths, use the setw manipulator. For example, if you want a number to be printed, right justified, in a column that is eight characters wide, you use << setw(8)

ENGR 1200U Winter 2013 - UOIT

20

There is a notable difference between the setprecision and setw manipulators. Once you set the precision, that width is used for all floatingpoint numbers until the next time you set the precision. But setw affects only the next value. Subsequent values are formatted without added spaces.

ENGR 1200U Winter 2013 - UOIT

Practice Example

Write this code


ENGR 1200U Winter 2013 - UOIT

21

#include <iostream> #include <string> using namespace std;

int main() { cout << "Enter your first name: "; string first; cin >> first; cout << "Enter your significant other's first name: "; string second; cin >> second; string initials = first.substr(0, 1) + "&" + second.substr(0, 1); cout << initials << endl; return 0; }

ENGR 1200U Winter 2013 - UOIT

22

Vous aimerez peut-être aussi