Lambda auto在c ++中输入函数给出错误

Lambda auto with input function in c++ giving errors

我正在尝试制作一个类似于 python input() 中的输入函数,但由于函数 return 变量的方式,它们必须采用函数类型 void, int, std::string 所以当用户输入一行时,它被设置为它必须 return 的值(即 int print() 意味着 return 也必须是 int 所以 9 = 57)。这是我当前的代码状态以及我想要发生的事情与正在发生的事情的示例。

//Input
auto input = [](const auto& message = "") {
    std::cout << message;
    const auto& x = std::cin.get();
    return x;
};

const auto& a = input("Input: ");
print(a);

使用当前代码,当我在控制台中键入 9 时,它 returns a as 57 .我希望它 return 它只是 9 但这显然不是我在键盘上键入的 int。它还 return 将输入 'string' 作为 115,我不知道为什么要这样做。最终我希望它像 pythons input() 和 return 一样作为字符串运行。 9 = 9 and 'string' = 'string.

std::cin.get(); 提取一个字符并且 returns 它的 ascii value 作为 int.

const auto& x = std::cin.get();时,插入'9',返回'9'的ascii值,即57.

'9' != 9.

在你的情况下 (ascii),'9'54
以同样的方式 's'"string" 的第一个字符)是 115.

const auto& x = std::cin.get(); return 一个 int。所以你的 lambda return 是一个整数,因此将你的字符打印为 int.

您可以使用 std::string:

std::string s;
std::cin >> s;
return s;

如果你想要像 python input() 这样的东西,我认为你应该在这种情况下硬编码 std::string 类型。

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); 

如果你输入一个整数,想要返回一个整数,你可以使用 stoi 转换它

auto b = std::stoi(input("Input: ")); //convert string to int, and b is an int
print(b); 

更新 由于 python input 一次读取整行,但是 std::cin >> x; 只会读到第一个 space、

std::getline(std::cin, x);//This will read the whole line including spaces

可能是更好的解决方案。

如果你想要更接近实际 Python 的 input() 函数的行为(实际上,raw_input() 因为你无法在这种情况下评估 Python ), 你可以这样做:

using EOFError = std::exception;

template <typename T = std::string>
std::string raw_input(T prompt = {}) {
  std::cout << prompt;
  std::string line;
  if (!std::getline(std::cin, line)) {
    throw EOFError();
  }
  return line;
}

这还将检测您何时收到 EOF(当 getline() 操纵的流不再有效时 - 理想情况下,您应该在此处检查 eofbit)。