Saturday, April 19, 2025

C++ Keyboard Input

This one will be useful and fun. We will get values from keyboard.

Run this code, and then we will explain: 

#include <iostream>

using namespace std;

int main() {

    int first_number;
    int second_number;
    int result;

    cout << "Please, enter First Number: " << endl;
    cin >> first_number;

    cout << "Please, enter Second Number :" << endl;
    cin >> second_number;

    result = first_number + second_number;

    cout << "Result: " << result << endl;

    return 0;

}

Result:

Please, enter First Number:
10
Please, enter Second Number :
20
Result: 30

Process returned 0 (0x0)   execution time : 5.078 s
Press any key to continue.

First we will have 3 variables. They will be without value at start. We need variable for result too. Integers, of course:

int first_number;
int second_number;
int result;

Then we are asking for first value to populate variable using cin (Character In) instruction. This is important to note, just as 2 right arrows:

cout << "Please, enter First Number: " << endl;
cin >> first_number;

Same approach with second number:

cout << "Please, enter Second Number :" << endl;
cin >> second_number;

Then we have addition:

result = first_number + second_number;

Time to print results: 

cout << "Result: " << result << endl;

Just don't forget that for printing we re using cout, and for taking stuff from keyboard we need cin command. Also, semicolons need to be at the end of all lines.

You can expand this approach even if you are at the start of programming career to do some calculations at the job or school. Just with this knowledge only we can do a lot.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...