Hello and welcome back. As a quick recap in my previous post, I discussed how we can output text with code. This is a snippet of code from the previous post -
#include<iostream>
using namespace std;
int main(){
cout<<"Coding with Ammar"; // Outputs on terminal
}
Now we are going to ask for input from the user. First, we will type our code as it is -
#include<iostream>
using namespace std;
int main(){
}
Now we are going to introduce to you a new function called "cin". This function takes input from the user and stores it in a variable. Here is the full code -
#include<iostream>
using namespace std;
int main(){
string name; // name is a variable type string.
int age; // age is a variable type integer.
// A variable stores data which is assigned to it until it is overwritten.
cout<<"Introduce yourself"<<endl;
// endl is a built in fuction and it puts the cursor on a new line.
cout<<"Enter your name: "; // Output Statement
cin>>name; // Input from user
cout<<"Enter your age: "; // Output Statement
cin>>age; // Input from user
cout<<"My name is "<<name<<" I am "<<age<<" years old.";// Output Statement
}
This code may be overwhelming at a glance but if you look closely we can understand almost 75% of this code easily. In the first few lines, you may be asking what "int" and "string" are. Well, those are datatypes to be exact. I will cover data types in my next post.
You may be wondering what is "endl". Well "endl" is a built-in function that puts our cursor at the next line. For example, if we have some consecutive outputs even typed on different lines it will print only on one line. So to prevent this we use endl.
You may be asking why we have multiple output statements. Well, we have them just to inform the user what they must type in a given input field. The output of this code will be -
You can also check this out on my YouTube channel -