0% found this document useful (0 votes)
8 views

Chapter Two- Programming I(C++)

Chapter 2 covers the basics of programming in C++, detailing the structure of a program from source code to executable file, including compilation and linking processes. It explains types of program errors, variable declaration, initialization, and the use of comments, as well as fundamental data types and string handling. Additionally, it introduces constants and literals, emphasizing the importance of valid identifiers and the case sensitivity of C++.

Uploaded by

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

Chapter Two- Programming I(C++)

Chapter 2 covers the basics of programming in C++, detailing the structure of a program from source code to executable file, including compilation and linking processes. It explains types of program errors, variable declaration, initialization, and the use of comments, as well as fundamental data types and string handling. Additionally, it introduces constants and literals, emphasizing the importance of valid identifiers and the case sensitivity of C++.

Uploaded by

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

Chapter 2

Basics of programming
Structure of a program
Structure of a program
• First, a text editor is used to save the C++ program in a text file. In other
words, the source code is saved to a source file.
• The source file is put through a compiler for translation.
• You must compile the source file. Compiling the source file generates an
object file.
• Finally, the linker combines the object file with other modules to form an
executable file. These further modules contain functions from standard
libraries or parts of the program that have been compiled previously.
• A program written in any other language needs to be first translated to the
machine language before it can be executed.
• A program written in a high-level language is translated to machine language
by a translator called a compiler. This process is said to compiling.
• How you will compile C++ source code depends upon your compiler and what
options you are using.
• Many compilers provide two different ways for compiling a program: the
command-line compiler and the Integrated Development Environment
(IDE). Thus, it is not possible to give generalized instructions for compiling a
C++ program.
• The output from a C++ compiler is executable object code.
• It is important to use the correct file extension for the source file’s name. the
most commonly found file extensions are .cpp and .cc.
• Prior to compilation, header files, which are also referred to as include files,
can be copied to the source file.
• Header files are text files containing information needed by various source
files,
e.g. type definitions or declarations of variables and functions.
• Header files can have the file extension .h, but they may not have any file
extension.
• When compile the program, the compiler will also issue warnings. A warning
does not indicate a syntax error but merely draws your attention to a possible error
in the program’s logic, such as the use of a non-initialized variable.
Type of program errors
• Syntax errors: are errors which occur due to violation of the syntax of grammar
rule of the programming language. It is detected by the compiler during compiling
time.
E.g. forgetting a semicolon at the end of each statement of C++, Miss Spell of key
word
Linker time error: Are an error which are detected during linking.
E.g. miss spell of the name main function, Missing object file
Run time error: are errors which occur while executing or running the program. It is
difficult to identify and correct. It also includes logical errors. Logical errors is an
error in which the program compile and run normally, but would give the wrong
answer.
E.g. infinite loop, dividing a number by the zero
First program
The best way to start learning a programming language is by writing a program.
// my first program in C++ Hello World!

#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!"<<endl;
return 0;
}

The first panel shows the source code for our first program. The second one shows the
result of the program once compiled and executed.
First program description
• // my first program in C++
This is a comment line.
• The line begins with the number symbol, #, which indicates that the line is
intended for the preprocessor.
• The preprocessor is just one step in the first translation phase and no object
code is created at this time.
#include <iostream>
• This allows the program access to all the information contained in the header
file.
• The header file iostream comprises conventions for input and output streams.
• The word stream indicates that the information involved will be treated as a
flow of data.
• All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std.
• Predefined names in C++ are to be found in the std (standard) namespace. The
using directive allows direct access to the names of the std namespace.
• Program execution begins with the first instruction in function main(), and this
is why each C++ program must have a main function.
• Apart from the fact that the name cannot be changed, this function’s structure is
not different from that of any other C++ function. In our example the function
main() contains two statements.
• The first statement
cout << “Hello world!" << endl;
outputs the text string Hello world! on the
screen. Structures function main()
The name cout (console output) designates an
object responsible for output. The two less-
than symbols, <<, indicate that characters are
being “pushed” to the output stream. Finally
endl (end of line) causes a line feed.
The statement
return 0;
terminates the function main() and also the
program, returning a value of 0 as an exit code
to the calling program.
It is standard practice to use the exit code 0 to
indicate that a program has terminated
correctly.
• The word main is followed in the code by a pair of parentheses (()). That is because
it is a function declaration:
• In C++, what differentiates a function declaration from other types of expressions
are these parentheses that follow its name. Optionally, these parentheses may enclose
a list of parameters within them.
• Right after these parentheses we can find the body of the main function enclosed in
braces ({}).
• Notice that the statement ends with a semicolon character (;).

All in just one line and this would have had exactly the same meaning as the previous
code.
int main () { cout << "Hello World!“<<endl; return 0; }
The division of code in different lines serves only to make it more legible and
schematic for the humans that may read it.
Comments in C++
• Comments are parts of the source code disregarded by the compiler. They simply
do nothing. Their purpose is only to allow the programmer to insert notes or
descriptions embedded within the source code.
• C++ supports two ways to insert comments
// line comment
This is known as line comment, discards everything from where the pair of slash
/* block comment */
The second one, known as block comment, discards everything between the /*
characters and the first appearance of the */ characters, with the possibility of
including more than one line.
Second program
e.g. Comments in C++
/* my second program
in C++ with more comments */

#include <iostream>
using namespace std;
int main (){
cout << "Hello World! "; // prints Hello World!
cout << "I'm a C++ program"; // prints I'm a C++
program
return 0;
}
Variables
a = 5;
b = 2;
a = a + 1;
result = a - b;
• In this code, the variable identifiers were a, b and result, but we could have
called the variables any names we wanted to create, as long as they were valid
identifiers.
Identifiers
• A valid identifier is a sequence of one or more letters, digits or underscore
characters (_).
• Neither spaces nor punctuation marks or symbols can be part of an identifier.
• Only letters, digits and single underscore characters are valid.
• Variable identifiers always have to begin with a letter and underline character
(_ ).
• In no case they can begin with a digit.
• Another rule that you have to consider when inventing your own identifiers is
that they cannot match any keyword of the C++ language nor your compiler's
specific ones, which are reserved keywords.
Keywords
• The standard reserved keywords are:
auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete,
do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend,
goto, if, inline, int, long, mutable, namespace, new, operator, private, protected,
public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct,
switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned,
using, virtual, void, volatile, wchar_t, while
• Very important: The C++ language is a "case sensitive" language. That means that
an identifier written in capital letters is not equivalent to another one with the same
name but written in small letters.
Thus, for example, the RESULT variable is not the same as the result variable or the
Result variable. These are three different variable identifiers.
Fundamental data types
• When programming, we store the variables in our computer's memory, but the
computer has to know what kind of data we want to store in them.
Name Descriptio Size* Range
n *
char Character or small integer. 1byte signed: -128 to 127
unsigned: 0 to 255
short int Short Integer. 2bytes signed: -32768 to 32767
(short) unsigned: 0 to 65535
signed: -2147483648 to
int Integer. 4bytes 2147483647
unsigned: 0 to 4294967295
signed: -2147483648 to
long int (long) Long integer. 4bytes 2147483647
unsigned: 0 to 4294967295
bool Boolean value. It can take one of two 1byte true or false
values: trueor false.
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
long double Long double precision floating point 8bytes +/- 1.7e +/- 308 (~15 digits)
number.
wchar_t Wide character. 2 or 1 wide character
4
byte
s
• The values of the columns Size and Range depend on the system the program is compiled for. The values
shown above are those found on most 32-bit systems.
• The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can
manage in C++. A byte can store a relatively small amount of data: one single character or a small integer
(generally an integer between 0 and 255).

Declaration of variables
• In order to use a variable in C++,
• we must first declare it specifying which data type we want it to be.
• The syntax to declare a new variable is to write the specifier of the desired data
type (like int, bool, float...) followed by a valid variable identifier.
e.g. int a;
float mynumber;
The first one declares a variable of type int with the identifier a.
The second one declares a variable of type float with the identifier mynumber.
• If you are going to declare more than one variable of the same type, you can
declare all of them in a single statement by separating their identifiers with
commas. For example:
int a, b, c;
This declares three variables (a, b and c), all of them of type int, and has exactly
the same meaning as

int a;
int b;
int c;
• The integer data types char, short, long and int can be either signed or unsigned
depending on the range of numbers needed to be represented.
• Signed types can represent both positive and negative values, whereas
unsigned types can only represent positive values (and zero).
• This can be specified by using either the specifier signed or the specifier
unsigned before the type name. For example:
unsigned short int NumberOfSisters;
signed int MyAccountBalance;
•By default, if we do not specify either signed or unsigned most compiler settings
will assume the type to be signed, therefore instead of the second declaration
above we could have written: int MyAccountBalance;
with exactly the same meaning (with or without the keyword signed)
• short and long can be used alone as type specifiers. Means short is equivalent to
short int and long is equivalent to long int.
short Year; short int Year;
• Finally, signed and unsigned may also be used as standalone type specifiers,
meaning the same as signed int and unsigned int respectively.
unsigned NextYear; unsigned int NextYear;
The above two declarations are equivalent
3rd program
// operating with variables
#include <iostream>
using namespace std;

int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;

// print out the result:


cout << result;

// terminate the program:


return
} 0;
Scope of variables
• All the variables that we intend to use in a program must have been declared
with its type specifier in an earlier point in the code, like we did in the previous
code at the beginning of the body of the function main when we declared that a,
b, and result were of type int
• A global variable is a variable declared in the main body of the source code,
outside all functions, while a local variable is one declared within the body of a
function or a block
• Global variables can be referred from anywhere in the code, even inside
functions, whenever it is after its declaration.
• The scope of local variables is limited to the block enclosed in braces ({})
where they are declared.
Initialization of variables
• When declaring a regular local variable, its value is by default undetermined.
But you may want a variable to store a concrete value at the same moment that
it is declared. In order to do that, you can initialize the variable.
There are two ways to do this in C++:
• The first one, known as c-like, is done by appending an equal sign followed by
the value to which the variable will be initialized:
Data type identifier = initial_value ; int a = 0;
• The other way to initialize variables, known as constructor initialization, is done
by enclosing the initial value between parentheses (()):
type identifier (initial_value) ; int a (0);
Both ways of initializing variables are valid and equivalent in C++
… Program
// initialization of variables

#include <iostream>
using namespace std;
int main ()
{ OUTPUT

int a=5; // initial value = 5


int b(2); // initial value = 2 6

int result;// initial value Undetermined


a = a + 3;
result = a - b;
cout << result;
return 0;
}
Strings
• Variables that can store non-numerical values that are longer than one single character are
known as strings.
• A first difference with fundamental data types is that in order to declare and use objects
(variables) of this type we need to include an additional header file in our source code:
<string> and have access to the std namespace
e.g.
// my first string
#include <iostream>
#include <string>
using namespace std;

int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
• Strings can be initialized with any valid string literal just like numerical type
variables can be initialized to any valid numerical literal.
e.g. Both initialization formats are valid with strings:
string mystring = "This is a string";
string mystring ("This is a string");
Strings can also perform all the other basic operations that fundamental data types can, like
being declared without an initial value and being assigned values during execution:
// my first string
#include<iostream>
#include <string>
using namespace std;
int
{ main ()
string mystring;
mystring = "This is the initial string content";
cout << mystring << endl;
mystring = "This is a different string content";
cout <<
return 0; mystring << endl;
}
Constants
• Constants are expressions with a fixed value.
Literals
• Literals are used to express particular values within the source code of a program.
• We have already used these previously to give concrete values to variables or to
express messages we wanted our programs to print out,
for example, when we wrote the 5 in this piece of code was a literal constant.
a = 5;
• Literal constants can be divided in Integer Numerals, Floating-Point Numerals,
Characters, Strings and Boolean Values.
Integer Numerals
• They are numerical constants that identify integer decimal values. Notice that to
express a numerical constant we do not have to write quotes (") nor any special
character. There is no doubt that it is a constant: whenever we write 1776 in a
program, we will be referring to the value 1776.
e.g. x=1779;
• In addition to decimal numbers (those that all of us are used to use every day)
C++ allows the use as literal constants of octal numbers (base 8) and
hexadecimal numbers (base 16).
• If we want to express an octal number we have to precede it with a 0 (zero
character). And in order to express a hexadecimal number we have to precede it
with the characters 0x (zero, x).
75 //decimal
0113 //octal
0x4b //hexadecimal
Floating Point Numbers

• They express numbers with decimals and/or exponents. They can include either a decimal point, an e
character (that expresses "by ten at the Xth height", where X is an integer value that follows the e
character), or both a decimal point and an e character:
3.14159 // 3.14159
6.02e23 // 6.02 x 10^23
1.6e-19 // 1.6 x 10^-19
3.0 // 3.0
•The default type for floating point literals is double. If you explicitly want to express a float or long
double numerical literal, you can use the f or l suffixes respectively:
3.14159L // long double
6.02e23f // float

Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be
written using either lower or uppercase letters without any difference in their meanings.
Character and string literals
• There also exist non-numerical constants, like:
'z'
'p'
"Hello world"
"How do you do?"
• The first two expressions represent single character constants, and the
following two represent string literals composed of several characters.
• Notice that to represent a single character we enclose it between single quotes
(') and to express a string (which generally consists of more than one character)
we enclose it between double quotes (").
• When writing both single character and string literals, it is necessary to put the
quotation marks surrounding them to distinguish them from possible variable
identifiers or reserved keywords.
x
'x'
Notice the difference between these two expressions:
x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed
within single quotation marks) would refer to the character constant 'x'.
• Character and string literals have certain peculiarities, like the escape codes.
These are special characters that are difficult or impossible to express otherwise
in the source code of a program, like newline (\n) or tab (\t). All of them are
preceded by a backslash (\). Here you have a list of some of such escape codes:
\n newline
\r carriage return
\t tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)
Boolean literals and Defined constants
• There are only two valid Boolean values: true and false. These can be expressed in C++
as values of type bool by using the Boolean literals true and false.
Defined constants (#define)
• You can define your own names for constants that you use very often without having to
resort to memory- consuming variables, simply by using the #define preprocessor
directive. Its format is:
#define identifier value
For example:
#define PI 3.14159 #define NEWLINE '\n‘
This defines two new constants: PI and NEWLINE. Once they are defined, you can use
them in the rest of the code as if they were any other regular constant,
• for example:
// defined constants: calculate circumference

#include <iostream>
using namespace std;

#define PI 3.14159
#define NEWLINE '\n'
int
{ main ()
double r=5.0;
31.4159
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}
Operators
• Assignment (=)
• Arithmetic operators ( +, -, *, /, % )
• Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
• Increase and decrease (++, --)
• Relational and equality operators ( ==, !=, >, <, >=, <= )
• Logical operators ( !, &&, || )
• Conditional operator ( ? )
• Comma operator ( , )
• Bitwise Operators ( &, |, ^, ~, <<, >> )
• Explicit type casting operator
• Other operators(Precedence of operators,)
Assignment operator
• The assignment operator assigns a value to a variable.
e.g. a=5; //This statement assigns the integer value 5 to the variable a.
• The part at the left of the assignment operator (=) is known as the lvalue (left
value) and the right one as the rvalue (right value).
• The lvalue has to be a variable whereas the rvalue can be either a constant, a
variable, the result of an operation or any combination of these.
• The most important rule when assigning is the right-to-left rule: The
assignment operation always takes place from right to left, and never the other
way:
e.g. a=b; This statement assigns to variable a (the lvalue) the value contained in
variable b (the rvalue).
• For example, let us have a look at the following code - I have included the
evolution of the content stored in the variables as comments:

This code will give us as result that the value contained in a is 4 and the one
contained in b is 7. Notice how a was not affected by the final modification of b,
even though we declared a = b earlier (that is because of the right-to- left rule).
• A property that C++ has over other programming languages is that the
assignment operation can be used as the rvalue (or part of an rvalue) for
another assignment operation.
•For example a = 2 + (b = 5); is equivalent to
b = 5;
a = 2 + b;
that means: first assign 5 to variable b and then assign to a the value 2 plus the
result of the previous assignment of b (i.e. 5), leaving a with a final value of 7.
•The following expression is also valid in C++:
a = b = c = 5;//It assigns 5 to the all the three variables: a, b and c.
Arithmetic operators ( +, -, *, /, % )
• Operations of addition, subtraction, multiplication and division literally
correspond with their respective mathematical operators.
• The only one that you might not be so used to see is modulo; whose
operator is the percentage sign (%).
• Modulo is the operation that gives the remainder of a division of two
values.
For example, if we write: a = 11 % 3;
• the variable a will contain the value 2, since 2 is the remainder from
dividing 11 between 3
Compound assignment
• (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
• When we want to modify the value of a variable by performing an operation
on the value currently stored in that variable we can use compound assignment
operators:
expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);

• And the same for all other operators.


Increase and decrease (++, --)
• the increase operator (++) and the decrease operator (--), increase or reduce by one the
value stored in a variable. They are equivalent to +=1 and to -=1, respectively.
e.g. c++;
c+=1;
c=c+1;
• Thus: are all equivalent in its functionality: the three of them increase by one the value
of c.
• A characteristic of this operator is that it can be used both as a prefix and as a suffix.
That means that it can be written either before the variable identifier (++a) or after it (a+
+).
• The increase operator is used as a prefix (++a) the value is increased before the result of
the expression is evaluated and therefore the increased value is considered in the outer
expression;
• Suffix (a++) the value stored in a is increased after being evaluated and therefore the
value stored before the increase operation is evaluated in the outer expression.
Example 1 Example 2

B=3; B=3;

A=++B; A=B++;

// A contains 4, B contains 4 // A contains 3, B contains 4

In Example 1, B is increased before its value is copied to A. While in


Example 2, the value of B is copied to A and then B is increased.
Relational and equality operators
• ( ==, !=, >, <, >=, <= )
• In order to evaluate a comparison between two expressions we can use the
relational and equality operators. The result of a relational operation is a
Boolean value that can only be true or false, according to its Boolean result.
Here there are some examples
== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to


• Instead of using only numeric constants, we can use any valid expression,
including variables. Suppose that a=2, b=3 and c=6,
• (a == 5) // evaluates to false since a is not equal to 5.
• (a*b >= c) // evaluates to true since (2*3 >= 6) is true.
• (b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
• ((b=2) == a) // evaluates to true. we first assigned the value 2 to b and then we
compared it to a, that also stores the value 2, so the result of the operation is
true.
Be careful!
The operator = (one equal sign) is not the same as the operator == (two equal
signs), the first one is an assignment operator (assigns the value at its right to the
variable at its left) and the other one (==) is the equality operator that compares
whether both expressions in the two sides of it are equal to each other.
Logical operators
• ( !, &&, || )
• The Operator ! is the C++ operator to perform the Boolean operation NOT, it
has only one operand, located at its right, and the only thing that it does is to
inverse the value of it, producing false if its operand is true and true if its
operand is false. Basically, it returns the opposite Boolean value of evaluating
its operand.
For example
!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is
true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
• The logical operators && and || are The operator || corresponds with Boolean
used when evaluating two logical operation OR. This operation
expressions to obtain a single results true if either one of its two
relational result.
operands is true, thus being false only
• The operator && corresponds with when both operands are false themselves.
Boolean logical operation AND. Here are the possible results of a
This operation results true if both its
|| b:
two operands are true, and false
otherwise. a b a || b

a b a && b true true true


true true true true false true
true false false false true true
false true false false false false
false false false
Conditional operator ( ? )
• The conditional operator evaluates an For example
expression returning a value if that
expression is true and a different one • 7==5 ? 4 : 3 // returns 3, since 7
if the expression is evaluated as is not equal to 5.
false. • 7==5+2 ? 4 : 3 // returns 4,
• Its format is: since 7 is equal to 5+2.
condition ? result1 : result2 • 5>3 ? a : b // returns the value
of a, since 5 is greater than 3.
• If condition is true the expression
will return result1, if it is not it will • a>b ? a : b // returns whichever
return result2 is greater, a or b.
… example program
// conditional operator • In this example a was 2 and b was 7, so the
expression being evaluated (a>b) was not
#include <iostream> true, thus the first value specified after the
using namespace std; question mark was discarded in favor of the
second value (the one after the colon) which
int main () was b, with a value of 7.
{
int a,b,c;

a=2; b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}
Exercise
1. Comma operator ( , )
2. Bitwise Operators ( &, |, ^, ~, <<, >> )
3. Explicit type casting operator
4. Other operators(Precedence of operators,)
Basic Input/Output
• Using the standard input and output library, we will be able to interact with the
user by printing messages on the screen and getting the user's input from the
keyboard.
• C++ uses a convenient abstraction called streams to perform input and output
operations in sequential media such as the screen or the keyboard.
• A stream is an object where a program can either insert or extract characters
to/from it.
• The standard C++ library includes the header file iostream, where the standard
input and output stream objects are declared.
Standard Output (cout)
• the standard output of a program is the screen, and the C++ stream object defined to access it is cout.
• cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs).
cout << "Output sentence"; // prints Output sentence on screen
cout << 120;// prints number 120 on screen
cout << x; // prints the content of x on screen
• The << operator inserts the data that follows it into the stream preceding it. In the examples above it
inserted the constant string Output sentence, the numerical constant 120 and variable x into the
standard output stream cout.
• Whenever we want to use constant strings of characters we must enclose them between double quotes
(") so that they can be clearly distinguished from variable names.
• For example, these two sentences have very different results:
cout << "Hello"; // prints Hello
cout << Hello; // prints the content of Hello variable
Standard Input (cin).
• The standard input device is usually the keyboard. Handling the standard input in C++ is done by

applying the overloaded operator of extraction (>>) on the cin stream.


• The operator must be followed by the variable that will store the data that is going to be extracted
from the stream.
• For example:
int age;
cin >> age;

• The first statement declares a variable of type int called age, and the second one waits for an input
from cin (the keyboard) in order to store it in this integer variable.
• cin can only process the input from the keyboard once the RETURN key has been pressed.
• If you request an integer you will get an integer, if you request a character you will get a character
and if you request a string of characters you will get a string of characters.
// i/o example 1

#include <iostream>
using namespace std;
Please enter an integer value: 702
The value you entered is 702 and its double is
int main ()
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i; 1404.
cout << " and its double is " << i*2 << ".\n";
return 0;
}
// cin with strings example2
In order to get entire lines, we can use the function getline, which is the
more recommendable way to get user input with cin
#include <iostream>
#include <string> What's your name? Juan
using namespace std; SouliÃ‾¿½ Hello Juan
SouliÃ‾¿½.
int main ()
{string mystr; What is your favorite team? The
cout << "What's your name? "; Isotopes I like The Isotopes too!
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!\n";
}return 0;
String stream
• The standard header file <sstream> defines a class called stringstream that allows a
string-based object to be treated as a stream.
• This way we can perform extraction or insertion operations from/to strings, which
is especially useful to convert strings to numerical values and vice versa.
• For example, if we want to extract an integer from a string we can write:
string mystr ("1204");
int myint;
stringstream(mystr)>> myint;
This declares a string object with a value of "1204", and an int object. Then we use
stringstream's constructor to construct an object of this type from the string object.
Because we can use stringstream objects as if they were streams, we can extract an
integer from it as we would have done on cin by applying the extractor operator (>>)
on it followed by a variable of type int.
y o u
a n k
T h

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy