检查输入是否是C ++中的数字或字符串

时间:2014-02-16 05:21:31

标签: c++ string integer user-input string-conversion

我写了下面的代码来检查输入(answer3)是一个数字还是字符串,如果它不是一个数字,它应该返回“仅输入数字”,但它返回相同的数字。请给我一个解决方案。

#include <iostream>
#include <string>
#include <typeinfo>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

using namespace std; 
int main ()
{

string ques1= "Client's Name :";
string ques2 = "Client's Address :";
string ques3 = "Mobile Number :";

char answer1 [80];
string answer2;
int answer3;

     cout<<ques1<<endl;    
     cin>>answer1;      

     cout<<ques2<<endl;    
     cin>>answer2; 

     cout<<ques3<<endl;
     cin>>answer3;

       if (isdigit(answer3))
       {
              cout<<"Correct"<<endl;     

              }

        else
        {
          cout<<"Enter Numbers Only"<<endl;  

            }

 system("pause>null");
 return 0;  

}

7 个答案:

答案 0 :(得分:7)

如果您使用的是C ++ 98 ,则可以使用stringstreams#include <sstream>):

std::string s = "1234798797";
std::istringstream iss(s);

int num = 0;

if (!(iss >> num).fail()) {
    std::cout << num << std::endl;
}
else {
    std::cerr << "There was a problem converting the string to an integer!" << std::endl;
}

如果您可以使用提升,则可以使用lexical_cast#include <boost/lexical_cast.hpp>):

std::string s = "1234798797";
int num = boost::lexical_cast<int>(si);//num is 1234798797
std::cout << num << std::endl;

如果您可以使用C ++ 11 ,则可以使用std::stoi中的内置<string> function

std::string s = "1234798797";
int mynum = std::stoi(s);
std::cout << mynum << std::endl;

输出:

1234798797

答案 1 :(得分:6)

您可以使用regex执行此操作:

#include <regex>

bool isNumber(std::string x){
    std::regex e ("^-?\\d+");
    if (std::regex_match (x,e)) return true;
    else return false;}

如果你想让isNumber()成为可以接受任何类型输入的通用函数:

#include <regex>
#include <sstream>

template<typename T>
bool isNumber(T x){
    std::string s;
    std::regex e ("^-?\\d+");
    std::stringstream ss; 
    ss << x;
    ss >>s;
    if (std::regex_match (s,e)) return true;
    else return false;}

以上isNumber()函数仅检查整数,精度的double或float值(包含点.)不会返回true。 如果您也想要精确度,请将regex行更改为:

std::regex e ("^-?\\d*\\.?\\d+");

如果您想要更高效的解决方案,请参阅this one

答案 2 :(得分:3)

函数 isdigit()用于仅测试数字(0,1,...,9)

使用此功能检查数字

bool is_number(const std::string& s)
{
    std::string::const_iterator it = s.begin();
    while (it != s.end() && std::isdigit(*it)) ++it;
    return !s.empty() && it == s.end();
}

答案 3 :(得分:1)

isdigit的输入是一个整数值。但是,仅当值对应于'0' - '9'时,它才会返回true(非零)。如果将它们转换为整数值,则为48-57。对于所有其他值,isdigit将返回false(零)。

您可以通过更改检查逻辑来检查是否有整数:

if ( cin.fail() )
{
   cout<<"Correct"<<endl;     
}
else
{
   cout<<"Enter Numbers Only"<<endl;  
}

答案 4 :(得分:1)

使用strtod的另一个答案:

bool isNumber(const std::string& s){
   if(s.empty() || std::isspace(s[0]) || std::isalpha(s[0])) return false ;
   char * p ;
   strtod(s.c_str(), &p) ;
   return (*p == 0) ;
}

能够处理任何类型的参数使用模板:

#include <sstream>

template<typename T>
bool isNumber(T x){
   std::string s;
   std::stringstream ss; 
   ss << x;
   ss >>s;
   if(s.empty() || std::isspace(s[0]) || std::isalpha(s[0])) return false ;
   char * p ;
   strtod(s.c_str(), &p) ;
   return (*p == 0) ;
}

注意:

  1. 空格会让它返回假。
  2. NANINF会使其返回false(确切地说,除了有效指数之外的任何字符都会使其返回false)。如果您想允许naninf,请删除|| std::isalpha(s[0])部分。
  3. 允许科学形式,即1e + 12将返回true。
  4. Double / float或integer将返回true。
  5. 这比regex answer更有效。 (正则表达很重)。

答案 5 :(得分:0)

兴趣现象是isdigit需要char投放到unsigned char。 (另见here)。

答案 6 :(得分:0)

这是一个有点老问题,但我想我会在我的代码中添加自己的解决方案。

检查字符串是否为数字的另一种方法是std::stod函数,已经提到过,但我使用它有点不同。在我的用例中,我使用try-catch块来检查输入是字符串还是数字,就像你的代码一样:

...
try {
    double n = stod(answer3);
    //This will only be reached if the number was converted properly.
    cout << "Correct" << endl;
} catch (invalid_argument &ex) {
    cout << "Enter Numbers Only" << endl;
}
...

此解决方案的主要问题是以数字(但不是所有数字)开头的字符串将转换为数字。这可以通过在返回的数字上使用std::to_string并将其与原始字符串进行比较来轻松解决。