Lesson 5 - C++ Cin & Strings
Lesson 5 - C++ Cin & Strings
C++ comes with libraries that provide us with many ways for performing input and
output. In C++ input and output are performed in the form of a sequence of bytes or
more commonly known as streams.
Input Stream: If the direction of flow of bytes is from the device(for example,
Keyboard) to the main memory then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device( display screen ) then this process is called output.
iostream: iostream stands for standard input-output stream. This header file
contains definitions to objects like cin, cout, cerr etc.
What is cin?
The cin object in C++ is an object of class istream. It is used to accept the input from
the standard input device i.e. keyboard. It is associated with the standard C input
stream stdin.
cin declaration
The cin object is used along with the extraction operator (>>) in order to receive a
The cin object can also be used with other member functions such as getline(), read(),
etc.
#include <iostream>
int main()
{
int x, y, z;
/* For single input */
cout << "Enter a number: ";
cin >> x;
Enter a number: 9
Enter 2 numbers: 1 5
Sum = 15
#include <iostream>
int main()
{
char name[20], address[20];
return 0;
}
You entered
Name = Sherlock Holmes
Address = Baker Street, UK
The extraction operator can be used on cin to get strings of characters in the same
way as with fundamental data types:
1 string mystring;
2 cin>>mystring;
To get an entire line from cin, there exists a function, called getline, that takes the
stream (cin) as first argument, and the string variable as second.
Example 3:
Notice how in both calls to getline, we used the same string identifier (mystr). What
the program does in the second call is simply replace the previous content with the
new one that is introduced.
stringstream
The standard header <sstream> defines a type called stringstream that allows a
string to be treated as a stream, and thus allowing extraction or insertion operations
from/to strings in the same way as they are performed on cin and cout. This feature is
most useful to convert strings to numerical values and vice versa. For example, in
order to extract an integer from a string we can write:
In order to use the string data type, the C++ string header <string> must be included
at the top of the program. Also, you’ll need to include using namespace std; to make
the short name string visible instead of requiring the cumbersome std::string. (As a
side note, std is a C++ namespace for many pieces of functionality that are provided in
standard C++ libraries. For the purposes of this class, you won't need to otherwise
know about namespaces.) Thus, you would have the following #include's in your
program in order to use the string type.
Example 4: