C++ 我想从用户那里获取一个数字,如果他键入字符或其他任何内容,我希望他再次输入该数字 intx; 如果(cin>>x) cout x; }
它假定让我再次输入数字,但它结束了程序,不再使用数字一个简单的解决方案是将输入作为C++ 我想从用户那里获取一个数字,如果他键入字符或其他任何内容,我希望他再次输入该数字 intx; 如果(cin>>x) cout x; },c++,C++,它假定让我再次输入数字,但它结束了程序,不再使用数字一个简单的解决方案是将输入作为字符串,使用正则表达式检查它是否是一个数字,是否将其转换为int,否则再次请求输入。下面是一个例子: int x; if(cin >> x) cout << "True" << endl; else { cin >> x; } #包括 #包括 #包括 int main(){ std::regex rx(R“((?:^|\s)([+-]?[[:dig
字符串
,使用正则表达式
检查它是否是一个数字,是否将其转换为int
,否则再次请求输入。下面是一个例子:
int x;
if(cin >> x)
cout << "True" << endl;
else
{
cin >> x;
}
#包括
#包括
#包括
int main(){
std::regex rx(R“((?:^|\s)([+-]?[[:digit:]+(?:\.[:digit:]+)(?=$|\s))”;
std::字符串行;
int n;
while(std::getline(std::cin,line)){
如果(标准::正则表达式匹配(行,接收)){
//输入是数字
n=标准::stoi(线);
std::coutcin>>x
不会返回false如果输入不是数字,你需要自己检查输入。你需要使用循环。使用goto语句:@Vincentgoto
如何解决他的问题?@Vincent它也不起作用
#include <iostream>
#include <string>
#include <regex>
int main() {
std::regex rx(R"((?:^|\s)([+-]?[[:digit:]]+(?:\.[[:digit:]]+)?)(?=$|\s))");
std::string line;
int n;
while ( std::getline(std::cin, line) ) {
if ( std::regex_match(line, rx) ) {
// Input is number
n = std::stoi( line );
std::cout << n << "\n";
break;
}
}
return 0;
}