gpt4 book ai didi

c++ - 检查 C++ 输入是否为整数的现代方法

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:56 24 4
gpt4 key购买 nike

我想添加用户无法在 reg 中输入非整数值的 checkin 我的 c++ 代码。如果他输入,则会再次提示他。我在 2011 年的堆栈溢出中看到了解决方案(How to check if input is numeric in C++)。现在有一些现代的或好的方法还是一样?

我尝试在 ctype.h 中使用 ifdigit()

// Example program
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
int x;
cout<<"Type X";
cin>>x;
if(!isdigit(x))
{
cout<<"Type Again";
cin>>x;
}
}

但是没用

这是我要添加检查的实际问题。

 cout << "Type Reg # of Student # " << i + 1 << endl;
do
{
cin >> arr[i][j];
} while (arr[i][j] < 999 || arr[i][j] > 9999);

其中 i 和 j 在 12 月。在 for 循环中。我只想添加检查输入是否不是字符串或类似的东西。不能依赖 2011 年的答案

最佳答案

查看下面的示例。

所有的魔法都发生在 to_num() 中,它将处理数字前后的空白。

#include <iostream>
#include <sstream>
#include <string>
#include <tuple>

auto to_num(const std::string& s)
{
std::istringstream is(s);
int n;
bool good = (is >> std::ws >> n) && (is >> std::ws).eof();

return std::make_tuple(n, good);
};

int main()
{
int n;
bool good;

std::cout << "Enter value: ";
for(;;)
{
std::string s;
std::getline(std::cin, s);

std::tie(n, good) = to_num(s);
if(good) break;

std::cout << s << " is not an integral number" << std::endl;
std::cout << "Try again: ";
}
std::cout << "You've entered: " << n << std::endl;

return 0;
}

to_num() 内部发生的事情的解释:

  1. (is >> std::ws >> n)is 中提取(可选)前导空格和一个整数。在 bool 上下文中 operator bool()如果提取成功,将启动并返回 true。

  2. (is >> std::ws).eof() 提取(可选的)尾随空格,如果末尾没有垃圾则返回 true。

更新

这是一个使用 Structured binding declaration 的稍微干净的版本和 Class template argument deduction在 c++17 中可用:

#include <iostream>
#include <sstream>
#include <string>
#include <tuple>

auto to_num(const std::string& s)
{
std::istringstream is(s);
int n;
bool good = (is >> std::ws >> n) && (is >> std::ws).eof();

return std::tuple(n, good); // look ma, no make_tuple
};

int main()
{
std::cout << "Enter value: ";
for(;;)
{
std::string s;
std::getline(std::cin, s);

auto [n, good] = to_num(s); // structured binding
if(good)
{
std::cout << "You've entered: " << n << std::endl;
break;
}
else
{
std::cout << s << " is not an integral number" << std::endl;
std::cout << "Try again: ";
}
}

return 0;
}

关于c++ - 检查 C++ 输入是否为整数的现代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57937891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com