I am trying to make an input function like the one in python input()
but because of the way functions return variables they must be in the format of the function type void, int, std::string
so when a user inputs a line it is set to what ever it must return (I.E. int print()
would mean the return also has to be int so 9 = 57). Here is my current state of code and an example of what I am wanting to happen vs what is happening.
//Input
auto input = [](const auto& message = "") {
std::cout << message;
const auto& x = std::cin.get();
return x;
};
const auto& a = input("Input: ");
print(a);
With this current code when I type 9 into the console it returns a
as 57. I was hoping it would return it as simply 9 but that is obviously not an int
as I typed it on my keyboard. It also returns the input 'string' as 115, I have no idea why it does this. Ultimately I would like it to function like pythons input()
and return it as a string. 9 = 9 and 'string' = 'string.
If you want something like python input()
, I think you should hard code a std::string
type in this case.
auto input = [](const std::string& message = "") {
std::cout << message;
std::string x;
std::cin >> x;
return x;
};
//print can be auto to be more generic
auto print = [](const auto& message) {std::cout << message << std::endl;};
auto a = input("Input: "); //a is a string
print(a);
If you input a int, and want an int back, you can convert it using stoi
auto b = std::stoi(input("Input: ")); //convert string to int, and b is an int
print(b);
UPDATE
Since python input
reads the whole line at once, but
std::cin >> x;
will only read until the first space,
std::getline(std::cin, x);//This will read the whole line including spaces
might be a better solution.