Wednesday, June 26, 2013

C++ (beginner) input and output functions

The standard input functions are
cin
cout
scanf
printf

cin

The form of cin function is

cin>>variable1>>variable2>>.....;

example
int a,b,c;
cin>>a>>b>>c;

the same goes for cout but for cout we put '<<' instead of '>>'

example

int a,b,c;
cin>>a>>b>>c;
cout<<a<<b<<c;

lets try to create this project together

open a new win32 console application, name it
then add a source file.


Type  the code from the picture above. 
Now lets run the code ( Ctrl+F5)
now input 3 numbers and press enter


As we can see we input 3 different number (1 2 3) but got 123 as a result.

The program didn't output wrong numbers he just output what we gave him, he outputed 3 numbers without separating them. for clearing this mistake we need to put spaces between numbers.

here is the corrected version, we only inserted 2 spaces betwenn the numbers.
If you want to print and enter after each number just do the following.

every time you cout endl it will hit an enter.

scanf and printf

These are a bit more complicated.
If you have a large input always use scanf and printf these function can read and write data 2 times faster than cin and cout. .
 example of scanf usage


in scanf between "  " we tell scanf what are we going t input
int this case %d means that we are going to input 1 integer,
%d%d%d means that we are going to input 3 integers.
& sigh is a special operator( see the intermediate section).
for now just remember that we need to put & sign in front of the variables we are going to read in scanf but not in front of the variables we are going to output.
as you can see there are spaces between %d in printf function.
in printf function between "  " we are telling printf what we want to output. It doesn't have to contain a variable at all , as in scanf we write %d to tell printf that we are going to print an integer then a space than an integer than a space again than an integer.
If you want to print enter use this sigh \n
example
printf("%d\n%d\n%d",a,b,c);
%d is for integers
but what if we want to input another data type variable
%f- for floats
%c- for characters
%I64d for long long type (__int64)

IF  YOU HAVE ANY QUESTIONS , LEAVE THEM IN COMMENTS, NO QUESTION WILL STAY UNANSWERED.

No comments:

Post a Comment