C++中检查输入是数字还是字符串

问题描述 投票:0回答:7

我编写了以下代码来检查输入(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;  

}
c++ string integer user-input string-conversion
7个回答
9
投票

您可以使用

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()
函数仅检查整数、双精度或带有精度的浮点值(包含点
.
)不会返回 true。 如果您也想要精度,请将
regex
行更改为:

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

如果您想要更有效的解决方案,请参阅这个


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;
}

如果您可以使用Boost,您可以使用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>
函数

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

输出:

1234798797

4
投票

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

使用此函数检查正整数(和零):

bool is_nonnegative_integer(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();
}

2
投票

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

你可以通过改变检查逻辑来检查你是否得到了一个整数:

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

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. 空格将使其返回 false。
  2. NAN
    INF
    会使其返回 false(准确地说,除了有效指数之外的任何字符都会使其返回 false)。如果您想允许
    nan
    inf
    ,请删除
    || std::isalpha(s[0])
    部分。
  3. 允许使用科学形式,即 1e+12 将返回 true。
  4. 双精度/浮点型或整数将返回 true。
  5. 这比正则表达式答案更有效。 (正则表达式很重)。

0
投票

有趣的现象是

isdigit
需要将
char
投射到
unsigned char
。 (另请参阅此处)。


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
并将其与原始字符串进行比较,可以轻松解决此问题。

© www.soinside.com 2019 - 2024. All rights reserved.