0% found this document useful (0 votes)
63 views81 pages

C Basics v3 PDF

This document provides an introduction to information systems for transportation. It discusses principles of algorithms, Turing machines, and programming languages. It also covers details of C++ programming including data types, variables, input/output, comments, namespaces, and naming conventions. The document provides resources for further reading on algorithms, programming languages, object-oriented programming, C++ standards, and secure coding best practices.

Uploaded by

Aldo Romei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views81 pages

C Basics v3 PDF

This document provides an introduction to information systems for transportation. It discusses principles of algorithms, Turing machines, and programming languages. It also covers details of C++ programming including data types, variables, input/output, comments, namespaces, and naming conventions. The document provides resources for further reading on algorithms, programming languages, object-oriented programming, C++ standards, and secure coding best practices.

Uploaded by

Aldo Romei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

INFORMATION SYSTEMS FOR

TRANSPORTATION
Introduction and basics
Principles

• Every problem that can be solved by an algorithm can be solved using a


Turing Machine.
• A Turing machine is a mathematical model of computation that defines an
abstract machine, which manipulates symbols on an infinite strip of tape
according to a table of rules.
• A system of data-manipulation rules (i.e. a computer's instruction set, a
programming language) is said to be Turing complete or computationally
universal if it can be used to simulate any Turing machine.

http://aturingmachine.com
What is an algorithm?
• An algorithm is a sequence of unambiguous instructions for solving a
problem, i.e., for obtaining a required output for any legitimate input
in a finite amount of time
• The instructions are in some language:
• I will teach you (a little) C++;
• the compiler translates those languages
to machine language

Compiler explorer https://godbolt.org


Programming languages
https://spectrum.ieee.org/at-work/innovation/the-2018-top-programming-languages

https://en.wikipedia.org/wiki/List_of_programming_languages

http://codetojoy.blogspot.com/2007/07/seven-wonders-of-programming-languages.html
The right language is not all
• Python with quicksort algorithm: elapsed time becomes 0.0021 s
• Can you choose a language that has the right tools?
Python is way better than C++ for text processing and file manipulation.
• Is your algorithm part of a standard library or a library you can download/buy?
Millions of programmers, just like you, have needed linear algebra algorithms.
Most of what you could need already exists!
http://www.hpc.cineca.it/content/introduction-object-oriented
https://www.geeksforgeeks.org/the-c-standard-template-library-stl/
https://en.cppreference.com/w/cpp/links
http://www.open-std.org/jtc1/sc22/wg21/docs/standards
Details
• C++ is standardized as ISO/IEC 14882. Currently, there are two versions:
• C++98 (ISO/IEC 14882:1998): First standard version of C++.
• C++03 (ISO/IEC 14882:2003): minor "bug-fix" to C++98 with no change to the language. Commonly
refer to as C++98/C++03 or First C++ standard.
• C++11 (ISO/IEC 14882:2011): Second standard version of C++. Informally called C++0x, as it
was expected to finalize in 200x but was not released until 2011. It adds some new features
to the language; more significantly, it greatly extends the C++ standard library and standard
template library (STL).
• C++14: Infomally called C++1y, is a small extension to C++11, with bug fixes and small
improvement.
• C++17: informally called C++1z.
• C++2a: the next planned standard in 2020.
Clean coding principles
• Use meaningful names (Try to figure out what f14() does)
• Code should be clear: Keep It Simple, Student (KISS)!
• Program units should have one clear function (Micorservices)
• Any functionality should be implemented only once:
Don't Repeat Yourself

• You can find solutions on the Internet: be sure to understand what


you're doing!
https://www.ioccc.org/index.html
Anonymous – IOCCC 2004

The output

The program
http://harmful.cat-v.org/software/c++/linus

http://www.stroustrup.com/ieee_interview.html
Rules for Developing Safe, Reliable, and Secure Systems
• There are rules to help programmers ensure that their C++ code
reduces security flaws by following secure coding best practices
https://www.securecoding.cert.org./confluence/pages/viewpage.action?pageId=88046682

• An example
Visual studio: tutorials…
https://tutorials.visualstudio.com/cpp-console/intro

https://visualstudio.microsoft.com/it/vs/getting-started/

https://blogs.msdn.microsoft.com/vcblog/2017/04/21/getting-started-
with-visual-studio-for-c-and-cpp-development/
File extensions
Edit, compile, run file.cc
Exercise: make a file with the following lines: file.cp
//#include “stdafx.h“ in visual studio file.cxx
#include <iostream> file.cpp
file.CPP
using namespace std;
file.c++
int main() { file.C
return 0; C++ source code
}
and compile it. file.h
file.hh
Run this program (it gives no output). file.H
file.hp
file.hxx
Add this line
file.hpp
file.HPP
cout << "Hello world!" << endl; file.h++
//system(“pause“); if the output window closes file.tcc
immediately
C++ header file
Details
• MAIN: In C the main function is always a free function that appears outside the context of any
class. in Java everything appears within the context of a class. C++ is an object-oriented
language like Java, but not everything in C++ is required to be object oriented.
• Include statements: System includes are denoted by the use of angle brackets around the
included file name and are used to import declarations related to the C++ standard library and
other resources. User includes are denoted by quote marks around the included file name are
used to import declarations stored in header files

#include <string>
#include "Example.h"
• Comments
//single row
/* ….. */
• Keywords (main, for, return…)
Details - Namespaces
• Java uses the package mechanism to reduce the potential for name conflicts. All classes are
required to belong to a package. Two classes with the same name can coexist, as long as the
two classes belong to separate packages.
• C++ namespaces serve the same purpose. To create a namespace
namespace MyStuff { // Declare classes, functions, and variables in here }
Since we are mostly going to be writing small programs in this course we won't need to create
namespaces frequently. Items that are not explicitly declared in a namespace land in the global
namespace.
• If you want to use something that was declared inside a namespace you have to do one among
1. std::string str = "Some text";
2. using std::string; // Import string from the std namespace, at the beginning or within a function body
3. using namespace std; // Imports names from the entire std space
• With 2 and 3 then
string str = "Some text"; // Now we can use string without std::
Details – I/O
• In C++ the expectation is that programmers will frequently write applications
that use text input and output in a console window. Consequently, C++ makes
it much easier to write console applications.
• The basic mechanism for doing text input and output is the iostreams facility.
To use this facility, you place the include statement
#include <iostream>
at the top of any source file where you want to do text input and/or output.
• To do text output, use the std::cout object in combination with the stream
injection operator <<. The endl output manipulator causes a line break in the
output, so that the next thing that gets output appears on the following line in
the output.
int x = 5; float y = 6.3;
std::cout << "x is " << x << " and y is " << y << std::endl;
A first example
Main: int or void?
• Normal exit is generally represented by 0.
• Abnormal termination is a non-zero value.
But there is no standard for how non-zero codes
are interpreted…
A second example
You can declare variables “everywhere” in the code.

1. Try inserting a longer (> 50) surname.

2. Try inserting a surname composed by two words.

3. Replace cin… with getline(cin, …) and


declare also surname as string
Variables

• Programs usually contain data stored in variables


• A variable has 1) a datatype, 2) a name, 3) a value.
• These are defined in a variable declaration and a variable assignment.
• The name = identifier has to start with a letter (or _ ), can contains
letters and digits, but NOT most special characters (except for _ ).
• For letters it matters whether you use upper or lowercase: the
language IS case sensitive.
Details
An identifier is needed to name a variable. C++ imposes the following rules on identifiers:
• An identifier is a sequence of characters, of up to a certain length (compiler-dependent), comprising uppercase and lowercase
letters (a-z, A-Z), digits (0-9), and underscore "_".
• White space (blank, tab, new-line) and other special characters (such as +, -, *, /, @, &, commas, etc.) are not allowed.
• An identifier must begin with a letter or underscore. It cannot begin with a digit. Identifiers beginning with an underscore are
typically reserved for system use. Don't use blank character in names. It is either not supported, or will pose you more challenges.
• An identifier cannot be a reserved keyword or a reserved literal (e.g.,int, double, if, else, for).
• Identifiers are case-sensitive. A rose is NOT a Rose, and is NOT a ROSE.
• Naming Convention: A variable name is a noun, or a noun phrase made up of several words. The first word is in lowercase, while
the remaining words are initial-capitalized, with no spaces between words. For example xMax, xTopLeft. This convention is also
known as camel-case.
• Recommendations
• It is important to choose a name that is self-descriptive and closely reflects the meaning of the variable,
e.g., numberOfStudents or numStudents.
• Do not use meaningless names like a, b, c, d, i, j, k, i1, j99, unless they are common names like x, y, z for coordinates, i for index.
• It is perfectly okay to use long names of says 30 characters to make sure that the name accurately reflects its meaning!
Variable declaration
• Declarations can go pretty much anywhere in your program, but need to
come before use of the variable.
• Name – datatype
float x;
int n1,n2;
• Name – datatype – value (declaration + initial assignment)
float x = 3.0 , y = 3.7 ;
• Do not use uninitialized variables! Doing so is legal, but there is no
guarantee about the initial value. Do not count on it being zero. . .
• const value: you have to initialize it because you will not able to do it later.
Fundamental datatypes
• Integers: C++ supports these integer types: char, short, int, long, long long (in C++11) in a non-decreasing order of size. The
actual size depends on the implementation. The integers (except char) are signed number (which can hold zero, positive and
negative numbers). You could use the keyword unsigned [char|short|int|long|long long] to declare an unsigned integers
(which can hold zero and positive numbers). There are a total 10 types of integers - signed|unsigned combined
with char|short|int|long|long long.
• Characters: Characters (e.g., 'a', 'Z', '0', '9') are encoded in ASCII into integers, and kept in type char. For example,
character '0' is 48 (decimal) or 30H (hexadecimal); character 'A' is 65 (decimal) or 41H (hexadecimal);
character 'a' is 97 (decimal) or 61H (hexadecimal). Take note that the type char can be interpreted as character in ASCII code,
or an 8-bit integer. Unlike int or long, which is signed, char could be signed or unsigned, depending on the implementation.
You can use signed char or unsigned char to explicitly declare signed or unsigned char.
• Floating-point Numbers: There are 3 floating point types: float, double and long double, for single, double and long double
precision floating point numbers. float and double are represented as specified by IEEE 754 standard. A float can represent a
number between ±1.40239846×10^-45and ±3.40282347×10^38, approximated. A double can represented a number
between ±4.94065645841246544×10^-324 and ±1.79769313486231570×10^308, approximated. Take note that not all real
numbers can be represented by float and double, because there are infinite real numbers. Most of the values are
approximated.
• Boolean Numbers: A special type called bool (for boolean), which takes a value of either true or false.
checking of overflow/underflow is the programmer's responsibility, i.e., your job!
Choosing Types
• Most of the times, the decision is intuitive. For example, use an integer type for counting and
whole number; a floating-point type for number with fractional part, char for a single
character, and boolean for binary outcome.
• Rule of Thumb: Use int for integer and double for floating point numbers.
Use byte, short, long and float only if you have a good reason to choose that specific precision.
• Use int (or unsigned int) for counting and indexing, NOT floating-point type (float or double).
This is because integer type are precise and more efficient in operations.
• char '1' is different from int 1, short 1, float 1.0, double 1.0
Float in IEEE 754: -1 x2 xM
S E
• char '1' is "00110001"
• short 1 is "00000000 00000001"
• int 1 is "00000000 00000000 00000000 00000001",
• float 1.0 is "0 01111111 0000000 00000000 00000000"
• double 1.0 is "0 01111111111 0000 00000000 00000000 00000000 00000000 00000000 00000000"
• long long 1 is "00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001"
• Details: http://www.ntu.edu.sg/home/ehchua/programming/java/DataRepresentation.html
User defined types
• Structure and classes, explained later
• Typedefs allow for creating new names (think of them as aliases) for
existing types. Following is the simple syntax to define a new type
using typedef:
• typedef int counter;
• counter tick_c = 100; // tick_c is a valid integer variable
• You can the use int or counter for variables: counter is an ALIAS!
• To create an enumeration requires the use of the keyword enum. The
general form of an enumeration type is:
• enum enum-name { list of names } var-list;
• enum colour {red, green, blue} a_colour, another_colour;
• a_colour = green; // a_colour will be assigned value of '1'
Assignments
An assignment statement:
• assigns a literal value (of the Right Hand Side) to a variable (of the LHS);
number = 8;
• or evaluates an expression (of the RHS) and assign the resultant value to a
variable (of the LHS)
number = 8 +1 ; number = a + 5; number = number / 1000;
• The symbol "=" is known as the assignment operator. The meaning of "=" in
programming is different from Mathematics. It denotes assignment instead
of equality, that is "==". Programmers are LAZY!
Literals (i.e. specific constant values)
• int number = -123;
• int number1 = 1234; // Decimal
• int number2 = 01234; // Octal 1234, Decimal 2322
• int number3 = 0x1abc; // hexadecimal 1ABC, decimal 15274
• int number4 = 0b10001001; // binary (may not work in some compilers)
• long number = 12345678L; // Suffix 'L' for long
• long sum = 123; // int 123 auto-casts to long 123L
• long long bigNumber = 987654321LL; // Need suffix 'LL' for long long int

• A long literal is identified by a suffix 'L' or 'l' (avoid lowercase, which can be confused with the
number one). A long long int is identified by a suffix 'LL'. You can also use
suffix 'U' for unsigned int, 'UL' for unsigned long, and 'ULL' for unsigned long long int.
Literals (i.e. specific constant values)
• A number with a decimal point, such as 55.66 and -33.44, is treated as
a double, by default. You can also express them in scientific notation,
e.g., 1.2e3, -5.5E-6, where e or E denotes the exponent in power of 10.
You could precede the fractional part or exponent with a plus (+) or minus
(-) sign. Exponent shall be an integer. There should be no space or other
characters (e.g., space) in the number.
• You MUST use a suffix of 'f' or 'F' for float literals, e.g., -1.2345F. For
example,
• float average = 55.66; // Error! RHS is a double. Need suffix 'f' for float.
• float average = 55.66f;Use suffix 'L' (or 'l') for long double.
Operations
• A printable char literal is written by enclosing the character with a pair
of single quotes, e.g., 'z', '$', and '9'. In C++, characters are represented using
8-bit ASCII code, and can be treated as a 8-bit signed integers in arithmetic
operations. In other words, char and 8-bit signed integer are
interchangeable. You can also assign an integer in the range of [-128, 127] to
a char variable; and [0, 255] to an unsigned char.
• char letter = 'a'; // Same as 97
• char anotherLetter = 98; // Same as the letter 'b’
• cout << letter << endl; // 'a' printed
• cout << anotherLetter << endl; // 'b' printed instead of the number
• anotherLetter += 2; // 100 or 'd’
• cout << anotherLetter << endl; // 'd' printed
• cout << (int)anotherLetter << endl; // 100 printed
Special form
• Update:
x = x+2; y = y/3;
// can be written as
x += 2; y /= 3;
• Integer add/subtract one:
i++; j--; /* same as: */ i=i+1; j=j-1;
• Pre/post increment:
x = a[i++]; /* is */ x = a[i]; i++;
y = b[++i]; /* is */ i++; y = b[i];
A third example
Input/output manipulators

• boolalpha | noboolalpha :
switches between textual and numeric representation of booleans
• showpos | noshowpos :
controls whether the + sign used with non-negative numbers
• dec | hex | oct :
changes the base used for integer I/O
• setw :
changes the width of the next input/output field
• fixed | scientific :
changes formatting used for floating-point I/O
• left | right :
sets the placement of fill characters
• Uppercase | nouppercase :
controls whether uppercase characters are used for exadecimal
and exponent
Exercise
• Write a program that has several variables.
• Assign values either in an initialization or in an assignment.
• Print out the values.
• Check overflows condition.
Solution - overflow
Expressions
• Expression looks pretty much like in math.
• With integers: 2+3
• with reals: 3.2/7
• Use parentheses to group 25.1*(37+42/3.)
• There is no `power' operator: library functions. Needs a line
• #include <cmath>
• http://www.cplusplus.com/reference/cmath/
• Modulus: %
• 5 % 2 → 1; -5 % 2 → -1
Expressions
Careful with types
• double pow (double base , double exponent);
• float powf (float base , float exponent);
• long double powl (long double base, long double exponent);
• You cannot omit the multiplication symbol '*’
is (1+2*a)/3 + (4*(b+c)*(5-d-e))/f - 6*(7/g+h).

• Real to integer: round down:


• double x,y; x = .... ; y = .... ;
• int i; i = x+y:
• Dangerous:
• int i,j; i = ... ; j = ... ;
• double x ; x = 1+i/j; //The fraction is executed as integer division.
• For floating point result do: (double)i/j /* or */ (1.*i)/j
Explicit type-casting
You can explicitly perform type-casting via the so-called unary type-
casting operator in the form of (new-type)operand or new-
type(operand). The type-casting operator takes one operand in the
particular type, and returns an equivalent value in the new type. Take
note that it is an operation that yields a resultant value, similar to an
addition operation although addition involves two operands.
You don't get the fractional part although the average is
a double. This is because both the sum and 100 are int.
The result of division is an int, which is then implicitly casted
to double and assign to the double variable average.

Correct version
Exercise
Converting between Celsius and Fahrenheit:
• Get a value in input
• Get if C or F
• Celsius = (5/9)(Fahrenheit–32)
• Fahrenheit = (9/5)Celsius+32
Solution
Don’t mix int and double!
• YES Double(9)/double(5)
• YES 9.0/5.0
• NO double (9/5)
Expressions
BOOLEAN
• Testing: == != < > <= >=
• Not, and, or: ! && ||
• if ( x>=0 && sqrt(x)<5 ) {}

BITWISE
• Bitwise: & | ^
• Bitwise operators are good for saving space
Arrays
• An array is a list of elements of the same type, identified by a pair of
square brackets [ ].
• To use an array, you need to declare the array with 3 things:
a name, a type and a dimension (or size, or length).
• The syntax is: type arrayName[arraylength];
• arraylength can be a literal or a variable
Arrays
• ATTENTION: you need to known the length (or size) of the array in advance, and
allocate accordingly. Once an array is created, its length is fixed and cannot be
changed. At times, it is hard to ascertain the length of an array (e.g., how many
students in a class?).
• This is probably the major drawback of using an array. C++ has a vector template
class (and C++11 added an array template class), which supports dynamic
resizable array. Otherwise use POINTERS.
• C/C++ does not perform array index-bound check. In other words, if the index is
beyond the array's bounds, it does not issue a warning/error. For example,
• int numbers[5];
// Can compiled and run, but could pose very serious side effect!
numbers[88] = 999;
cout << numbers[77] << endl; // What happens? Try it
Arrays
// Declare and initialize an int array of 3 elements
int numbers[3] = {11, 33, 44};
// If length is omitted, the compiler counts the elements
int numbers[] = {11, 33, 44};
// Number of elements in the initialization shall be equal to or less than length
int numbers[5] = {11, 33, 44}; // Remaining elements are zero. Confusing! Don't do this
int numbers[2] = {11, 33, 44}; // ERROR: too many initializers
// Use {0} or {} to initialize all elements to 0
int numbers[5] = {0}; // First element to 0, the rest also to zero
int numbers[5] = {}; // All element to 0 too
Multi-dimensional array
• int[2][3] = { {11, 22, 33}, {44, 55, 66} };
• For 2D array (table), the first index is the row number, second index is the
column number. The elements are stored in a so-called row-
major manner, where the column index runs out first.
• Pay attention to the performance!
• Use linear array:
Declare a[rows*cols]
p[ (1*cols) + 2] = 1
//equivalent to a[1][2] = 1;
Strings
• C++ supports two types of strings:
• the original C-style string: A string is a char array, terminated with
a NULL character '\0' (Hex 0). It is also called Character-String or C-style string.
• the new string class introduced in C++98. Later..
• The "high-level" string class is recommended, because it is much
easier to use and understood. However, many legacy programs used
C-strings; many programmers also use "low-level" C-strings for full
control and efficiency; furthermore, in some situation such as
command-line arguments, only C-strings are supported. Hence, you
may have to understand both sets of strings. However, avoid C-string
unless it is absolutely necessary.
C-String
A string is a char array terminated by a NULL character '\0'
Example
Structures
• structure is another user defined data type which allows you to
combine data items of different kinds.
• Structures are used to represent a record: suppose you want to keep
track of your books in a library.
• struct [structure tag] {
member definition;
...
member definition; } [one or more structure variables];
Pointers

• A pointer is essentially a simple integer variable which holds a memory


address that points to a value, instead of holding the actual value itself.
• The computer's memory is a sequential store of data, and a pointer points
to a specific part of the memory.
• Can be untyped
void * v; // can point to any type
• However, usually they’re typed
• Checked by compiler
• Can only be assigned addresses of variables
of the type to which it can point
int * p; // can only point to int
• p <> q , *p == *q
Dereferencing
• Dereferencing is the act of referring to where the pointer points, instead of the
memory address.
• We are already using dereferencing in arrays - but we just didn't know it yet. The
brackets operator - [0] for example, accesses the first item of the array. And since
arrays are actually pointers, accessing the first item in the array is the same as
dereferencing a pointer.
• Dereferencing a pointer is done using the asterisk operator *.
• int a = 1;
int * pointer_to_a = &a; // assign the address of a, not its value
a += 1; // value of a is 2
*pointer_to_a += 1; // value of a is 3
Pay attention
• Variables are not automatically given an intial value by the system, and start with
whatever garbage is left in memory when they are allocated. Pointers have the potential
to cause substantial damage when they are used without a valid address.
For this reason it's important to initialize them.
• NULL. The standard initialization is to the predefined constant NULL. Using the NULL
value as a pointer will cause an error on almost all systems, making the debugging
process somewhat easier.
The NULL pointer is a constant with a value of zero defined in several standard libraries,
including iostream and cstdlib.
• Try
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;
• Read also
https://embeddedartistry.com/blog/2017/2/28/migrating-from-c-to-c-null-vs-nullptr
Pointers and arrays
• int *A;
… later in the code ….
A = new int[100]; // A points to an array of 100 int
• If you created the array via the newoperation, you will need to
explictly make the array go away when you are done with it by using
the delete[] operator:
delete[] A;
Example

Why these results?

3 3 0x1514010
4 4 0x1514014
5 5 0x1514018

0 0x1514014
Pointers and structures

• See the use of typedef

• -> instead of . to access the fields


Exercise
1. Change the previous program by using an array of two books, e.g. myBook[0] and myBook[1];
2. Create an array of values and compute the max, min and average value.
Solution for 1

Equivalent way to access the elements


• strcpy( (*(myBook+1)).title, "Telecom Billing");
• strcpy( (myBook+1)->author, "Yakit Singha");
• strcpy( myBook[1].subject, "Telecom");
Scope
Block scope
Namespace
Flow Control
There are three basic flow control constructs -
sequential, conditional (or decision), and loop (or iteration)
Conditional flow
You could omit the braces { }, if there is only one statement inside the block.

NOTE o check for a null pointer


you can use an if statement
if(ptr) // succeeds if p is not null
if(!ptr) // succeeds if p is null
Conditional flow

"switch-case" is an alternative to the "nested-if". You can use either an int or char variable as the case-selector.
In a switch-case statement, a break statement is needed for each of the cases. If break is missing, execution will flow
through the following case.
Conditional Operator: A conditional operator is a ternary (3-operand) operator, in the form
booleanExpr ? trueExpr : falseExpr.
max = (a > b) ? a : b;
abs = (a > 0) ? a : -a;
Loop flow

The difference between while-do and do-while lies in the order of the body and condition.
In while-do, the condition is tested first. The body will be executed if the condition is true and the process
repeats. In do-while, the body is executed (at least once ) and then the condition is tested.
Interrupting Loop Flow - "break" and "continue"
• The break statement breaks out and exits the current (innermost) loop.
• The continue statement aborts the current iteration and continue to the next iteration of the current loop.
• These are poor structures as they are hard to read and hard to follow. Different solutions exist.
Command-line arguments
• The full declaration of main looks like this:
int main ( int argc, char *argv[] )
• The integer, argc is the ARGument Count (hence argc). It is the
number of arguments passed into the program from the command
line, including the name of the program.
• The array of character pointers is the listing of all the arguments.
argv[0] is the name of the program. After that, every element number
less than argc is a command line argument.
• You can use each argv element just like a string, or use argv as a two
dimensional array.
Example
#include <iomanip> test\a.exe "Peter Piper" picked a
#include <iostream> peck of "pickled peppers "
using namespace std;
The name used to start the program:
test\a.exe
int main( int argc, char* argv[] )
Arguments are:
{ 1: Peter Piper
cout << "The name used to start the program: " << argv[ 0 ] 2: picked
<< "\nArguments are:\n"; 3: a
for (int n = 1; n < argc; n++) 4: peck
5: of
cout << setw( 2 ) << n << ": " << argv[ n ] << '\n';
6: pickled peppers
return 0;
}
Exercise
• Take in input via shell 3 parameters: number1 number2 operation
(*+-/)
• Perform the operation and print to the screen the resut

• Use
• Argc and argv (slide 80)
• Switch (slide 76)
• atoi(argv[1]) and include cstdlib
• Op = argv[3][0]
#include "stdafx.h"
#include <iostream>
Solution cout << "The result of " << op << " is: ";
#include <cstdlib>
using namespace std; switch (op) {
case '+':
cout << x + y << endl; break;
int main(int argc, char* argv[]) { case '-':
if (argc != 4) { cout << x - y << endl; break;
cout << "usage: program num1 num2 op" case '*':
<< endl; cout << x * y << endl; break;
system("pause"); case '/':
return -5; cout << x / y << " (and % " << x%y << " ) " << endl; break;
} default:
cout << "Wrong operation\n"; break; return -6;
}
int x = atoi(argv[1]);
int y = atoi(argv[2]); system("pause");
char op = argv[3][0]; return 0;
}

You might also like