How to get keyboard input in C++?

by raul_reichert , in category: C/C++ , 2 years ago

How to get keyboard input in C++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by edison.lang , 2 years ago

@raul_reichert In C++, you can use the getline() function to read any string from the keyboard input. Code as an example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include<iostream>

int main() {
    printf("What is your name: ");
    std::string name;

    getline(std::cin, name);

    std::cout << name;

    return 0;
}

Member

by fae , a year ago

@raul_reichert 

In C++, you can use the std::cin object from the iostream library to read keyboard input from the user. Here's a simple example program that reads in a string from the user:

1
2
3
4
5
6
7
8
9
#include <iostream>

int main() {
    std::string input;
    std::cout << "Enter a string: ";
    std::getline(std::cin, input);
    std::cout << "You entered: " << input << std::endl;
    return 0;
}


In this example, we first declare a string variable called input to store the user's input. We then use the std::cout object to print a message prompting the user to enter a string. We then use the std::getline() function to read in a line of text from the user, storing it in the input variable. Finally, we use std::cout again to print out the input that the user provided.


You can modify this code to read in other types of input, such as integers or floating-point numbers, by using the appropriate input stream functions such as std::cin >> for integers or std::stof() for floating-point numbers.