Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我想从用户那里获取一个数字,如果他键入字符或其他任何内容,我希望他再次输入该数字 intx; 如果(cin>>x) cout x; }_C++ - Fatal编程技术网

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::cout
cin>>x
不会返回false如果输入不是数字,你需要自己检查输入。你需要使用循环。使用goto语句:@Vincent
goto
如何解决他的问题?@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;
}