How to Input a number and print the result in C++ ?


To input a number and print the result in C++, you can use the cin and cout functions respectively. Here's an example:

#include <iostream>

using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "The number you entered is: " << num << endl;
    return 0;
}

In this example, we first declare an integer variable num. We then use the cout function to display a message asking the user to enter a number. We then use the cin function to read the user's input and store it in the num variable. Finally, we use the cout function again to display the value of num.

Another way to input a number and print the result in C++ is to use the getline function. Here's an example:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string input;
    int num;
    cout << "Enter a number: ";
    getline(cin, input);
    num = stoi(input);
    cout << "The number you entered is: " << num << endl;
    return 0;
}

In this example, we first declare a string variable input and an integer variable num. We then use the cout function to display a message asking the user to enter a number. We then use the getline function to read the user's input as a string and store it in the input variable. We then use the stoi function to convert the string to an integer and store it in the num variable. Finally, we use the cout function again to display the value of num.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.