当用户在字符数组中输入整数值时捕获异常

时间:2017-01-27 01:02:55

标签: c++

所以我的问题是如果我有一个字符数组,我只允许在其中输入字符。如果我输入带字符的整数,请假设" abc123"那不应该被允许。怎么做我这样做?

1 个答案:

答案 0 :(得分:0)

使用std::none_of以及isdigit

#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>

int main()
{
   std::string test = "abc123";
   if ( std::none_of(test.begin(), test.end(), ::isdigit))
      std::cout << "All good\n"; 
   else
      std::cout << "You've entered an integer\n";

   // Try with good data
   test = "abcdef";
   if ( std::none_of(test.begin(), test.end(), ::isdigit))
      std::cout << "All good\n"; 
   else
      std::cout << "You've entered an integer\n";    
} 

Live Example