————————————————–
#include <iostream.h>
int main()
{
int num1;
cout<<”Enter a number: “;
cin>>num1;
cout<<”You
entered the number “<<num1;
return 0;
}
————————————————–
Cin stands for Console Input (as explained in the Hello World program.). Note: I have explained a lot of Useful things in our Hello World Program, So if you haven’t read it and skipped to this, It would be useful to read it if you have no knowledge of cin.
- cin>>num1;
- cout<<”You entered the number “<<num1;
To take in character input, we could do the same thing:
————————————————–
#include <iostream.h>
int main()
{
char name;
cout<<”Enter your name: “;
cin>>name;
cout<<”Your name is “<<name;
return 0;
}
————————————————–
This is similar. However, if the user types in something with a space e.g.
Super Man
The console will only print out:
Your name is Super
Instead of:
Your name is Super Man
To correct this problem ,we do this:
————————————————–
#include <iostream.h>
int main()
{
char name [13];
cout<<”Enter your name: “;
cin.getline(name,13);
cout<<”Your name is “<<name;
return 0;
}
char name [13];
————————————————–
This means that the user can enter a maximum of 12 characters. Why 12? Well this is because we have something called the NULL character. It is included because it is the space that we entered. So when the user type’s in a space, that is the NULL character.
So we want the user to type in a maximum of 5 letters, we must do:
char name[6];
cin.getline(name,6);
console output.getline(cin.getline) is what we type when we want the user to type in something with a space.5 is the maximum amount of letters it can have, of course we typed in 6 due to thenull character.
so back to our program:
cin.getline(name,13);
cout<<”Your name is “<<name;
When we want to include more text after typing in <<name, we can do this:
cout<<”I think your name is “<<name<<”,Right?”;
At runtime the text will be:
I think your name is blah, right?
after typing in name, we type in the <<operator and then text.
————————————————-
So I’ve gone through some basic things a C++ program should have. I tried to make this tutorial as detailed as possible. You should note that you need a C++ compiler. I recommend Dev-C++.
0 comments:
Post a Comment