Beruflich Dokumente
Kultur Dokumente
Keil 1/03 1
C-style strings
Character data • String literals use double quotes
• A character’s data type is char • char s[20]; declares a char array (string)
• A string is a sequence of • Null character terminates a string
characters • Strings must be manipulated with libraries
such as string.h
• A standard string class is • Input: cin >> s;
evolving • Output: cout << s;
• The C-language input/output • Initialization: char s[ ] = “Foo”;
library is stdio.h • Conversions: atoi, atof (stdlib.h)
David Keil 1/03 15 David Keil 1/03 16
Static variables
Sum-1-to-n problems • A static variable is initialized once
• Write a function that returns • Example:
int new_ID() .
the sum of all values from // Returns a unique ID number
1 to parameter n. {
static int ID = 0;
Argument Return value ++ID;
1 1 return ID;
2 3 }
3 6 • Keyword static is a storage-class qualifier
4 10 • Storage duration of static variable is execution of
program; for automatic variable duration is
• Now, write a recursive version. execution of function
David Keil 1/03 53 David Keil 1/03 54
1. Types, loops, subprograms CS II D. Keil 1/03 10
void main()
Stubs test a top-down design
{
char option;
do {
A menu void add() { cout << "Calling <add>" << endl; }
cout << "1 Add" << endl
<< "2 Subtract" << endl
presents void
void
void
subtract() { cout << "Calling <subtract>" << endl; }
multiply() { cout << "Calling <multiply>" << endl; }
divide() { cout << "Calling <divide>" << endl; }
<< "3 Multiply" << endl Menu
<< "4 Divide" << endl
<< "5 Quit" << endl;
user void main()
{ Stub function definitions
cout << “Choose operation: “;
cin >> option; options char option;
do {
if (option >= '1' && option <= '4')
cout << "1 Add" << endl << "2 Subtract" << endl
{
<< "3 Multiply" << endl << "4 Divide" << endl
cout << "Enter two integers: ";
<< "5 Quit" << endl;
int input1,input2;
cin >> option;
cin >> input1 >> input2;
if (option != '5')
switch (option) {
{
case '1': cout << input1 + input2 << endl; break;
switch (option) Calls to stub
{
case '2': cout << input1 - input2 << endl; break;
case '1': add(); break; functions
case '3': cout << input1 * input2 << endl; break;
case '2': subtract(); break;
case '4': cout << input1 / input2 << endl; break; case '3': multiply(); break;
} case '4': divide(); break;
} }
} while (option != '5'); }
}
} while (option != '5');
[menu.cpp ] [stub.cpp]
David Keil 1/03 61 } David Keil 1/03 62
Command-line arguments
• argc: how many command
parameters
• argv: an array of strings
• argv[1]: the first command-line
argument
• Applications: file names, switches
void main(int argc,char **argv)
{
for (int i=0; i < argc; ++i)
cout << argv[i] << “ “;
}
Output: [The command line, verbatim] David Keil 1/03 63