C++ Lambda auto,具有c+中的输入功能+;出错
我试图创建一个类似python中的输入函数C++ Lambda auto,具有c+中的输入功能+;出错,c++,input,lambda,return,auto,C++,Input,Lambda,Return,Auto,我试图创建一个类似python中的输入函数input(),但由于函数返回变量的方式,它们必须采用函数类型void,int,std::string的格式,因此当用户输入一行时,它被设置为必须返回的内容(即int print()意味着返回值也必须为int(因此9=57)。下面是我当前的代码状态,以及我希望发生什么和正在发生什么的示例 //Input auto input = [](const auto& message = "") { std::cout << messa
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);
//输入
自动输入=[](const auto&message=“”){
std::coutstd::cin.get();
提取字符并将其作为int
返回
写入const auto&x=std::cin.get();
并插入'9'
时,返回'9'
的ascii值,即57
'9'
!=9
在您的示例(ascii)中,'9'
是54
同样地,“string”
的第一个字符是115
const auto&x=std::cin.get();
返回一个int
。因此lambda返回一个int,并将字符打印为int
您可以使用std::string
:
std::string s;
std::cin >> s;
return s;
如果您想要pythoninput()
,我认为在本例中应该硬编码一个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);
更新
因为pythoninput
一次读取整行,但是
std::cin>>x;
将只读取到第一个空格
std::getline(std::cin, x);//This will read the whole line including spaces
可能是一个更好的解决方案。如果您希望行为更接近实际Python的input()
函数(实际上,raw\u 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;
}
使用EOFError=std::exception;
模板
字符串原始输入(T提示符={}){
std::cout Thank!这是一个函数,但我希望它能像pythons版本一样工作。在这种情况下,您必须输入,否则当您按enter键时,它会继续询问(出于某种原因,空格也不算作字符)。在python中,如果您在没有输入的情况下按enter键,它将继续。使用.get()
方法会这样做,但只会将第一个字符记录为@Gill Bates提到的字符。有没有办法实现这一点?很好!有没有办法允许std::cin
不接受输入并在按下enter键时关闭?此时它将继续询问,直到出现一个字符(不包括空格)请注意,在python中,无论什么时候按下enter键,它都会关闭,默认情况下,它只会从字符串中提取第一个标记,例如,在第一个空格处停止。这也会吞噬换行符(即空格),因此您无法捕捉到它。@Mose我认为std::getline(std::cin,x)
可能会完成这项工作!我已更新了答案,请告诉我您是否正在寻找答案for@Mose请看jmc的答案,它更接近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;
}