代码之家  ›  专栏  ›  技术社区  ›  Mose

c++中带有输入函数的Lambda auto给出错误

  •  2
  • Mose  · 技术社区  · 6 年前

    我正在尝试创建一个类似python中的输入函数 input() 但由于函数返回变量的方式,它们必须采用函数类型的格式 void, int, std::string 因此,当用户输入一行时,它被设置为必须返回的内容(即。 int print() 这意味着回报也必须为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 返回控制台 a 57 .我希望它能简单地返回 9 但这显然不是 int 当我在键盘上打字时。它还返回输入“string”,如下所示 115 ,我不知道它为什么会这样。最终我希望它能像蟒蛇一样工作 输入() 并将其作为字符串返回。9=9且“string”=“string”。

    4 回复  |  直到 6 年前
        1
  •  2
  •   gchen    6 年前

    如果你想要python之类的东西 input() ,我想你应该硬编码a 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); 
    

    如果您输入一个int,并且想要返回一个int,您可以使用stoi转换它

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

    使现代化 自python以来 input 一次读取整行,但是 std::cin >> x; 将只读取到第一个空格,

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

    可能是更好的解决方案。

        2
  •  1
  •   Kostas    6 年前

    std::cin.get(); 提取字符并返回其 ascii value 作为 int

    当你写作时 const auto& x = std::cin.get(); '9' 插入时,ascii值为 “9” 返回,即 57

        3
  •  1
  •   Jarod42    6 年前

    '9' 哦= 9

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

    const auto& x = std::cin.get(); 返回 int 。因此,lambda返回一个int,然后将角色打印为 内景

    您可以使用 std::string :

    std::string s;
    std::cin >> s;
    return s;
    
        4
  •  1
  •   jmc    6 年前

    如果希望行为更接近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 此处)。