在 C++ 中检查输入是数字还是字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21807658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if the input is a number or string in C++
提问by WESTRUK
I wrote the following code to check whether the input(answer3) is a number or string, if it is not a number it should return "Enter Numbers Only" but it returns the same even for numbers. Please suggest me a solution.
我编写了以下代码来检查 input(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;
}
回答by Jahid
You can use regex
to do this:
您可以使用以下regex
方法执行此操作:
#include <regex>
bool isNumber(std::string x){
std::regex e ("^-?\d+");
if (std::regex_match (x,e)) return true;
else return false;}
If you want to make isNumber()
a generic function which can take any type of input:
如果你想创建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;}
The above isNumber()
function checks for integer only, double or float value with precision (which contains dot .
) will not return true.
If you want precision too, then change the regex
line to:
上述isNumber()
函数仅检查整数、双精度或浮点值(包含点.
)不会返回 true。如果您也想要精度,则将regex
行更改为:
std::regex e ("^-?\d*\.?\d+");
If you want a more efficient solution, see this one.
如果您想要更有效的解决方案,请参阅此。
回答by jrd1
If you're using C++98, you can use stringstreams
(#include <sstream>
):
如果您使用的是 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;
}
If boost is available to you, you can use lexical_cast(#include <boost/lexical_cast.hpp>
):
如果你可以使用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;
If C++11 is available to you, you can use the builtin std::stoi
functionfrom <string>
:
如果C ++ 11是提供给你,你可以使用内置std::stoi
函数从<string>
:
std::string s = "1234798797";
int mynum = std::stoi(s);
std::cout << mynum << std::endl;
OUTPUTS:
输出:
1234798797
回答by Chethan N
The function isdigit()is used to test for only digits ( 0,1,...,9)
函数isdigit()仅用于测试数字(0,1,...,9)
use this function to check for numbers
使用此函数检查数字
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();
}
回答by R Sahu
The input to isdigit
is an integer value. However, it will return true (non-zero) only if the value corresponds to '0'-'9'. If you convert them to integer values, they are 48-57. For all other values, isdigit
will return false (zero).
输入到isdigit
是一个整数值。但是,只有当值对应于“0”-“9”时,它才会返回真(非零)。如果将它们转换为整数值,则它们是 48-57。对于所有其他值,isdigit
将返回 false(零)。
You can check whether you got an integer by changing checking logic:
您可以通过更改检查逻辑来检查是否获得了整数:
if ( cin.fail() )
{
cout<<"Correct"<<endl;
}
else
{
cout<<"Enter Numbers Only"<<endl;
}
回答by Jahid
Another answer using strtod
:
另一个答案使用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) ;
}
To be able to handle any type of parameter use template:
为了能够处理任何类型的参数使用模板:
#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) ;
}
Note:
笔记:
- White space will make it return false.
NAN
andINF
will make it return false (to be exact, any character except valid exponent will make it return false). If you want to allownan
andinf
, delete the|| std::isalpha(s[0])
part.- scientific form is allowed i.e 1e+12 will return true.
- Double/float or integer will return true.
- This is more efficient than the regex answer. (regex is heavy).
- 空白将使其返回 false。
NAN
并且INF
将使它返回false(准确的说,除了有效指数的任何字符将使其返回false)。如果要允许nan
和inf
,请删除该|| std::isalpha(s[0])
部分。- 允许使用科学形式,即 1e+12 将返回 true。
- Double/float 或 integer 将返回 true。
- 这比正则表达式答案更有效。(正则表达式很重)。
回答by MarkSill
This is a somewhat old question, but I figured I'd add my own solution that I'm using in my code.
这是一个有点老的问题,但我想我会添加我在我的代码中使用的自己的解决方案。
Another way to check if a string is a number is the std::stod
function, which has been mentioned, but I use it a bit differently. In my use case, I use a try-catch block to check if the input is a string or number, like so with your code:
另一种检查字符串是否为数字的方法是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;
}
...
The primary problem with this solution is that strings that begin with numbers (but aren't all numbers) willbe converted to numbers. This can be easily fixed by using std::to_string
on the returned number and comparing it to the original string.
此解决方案的主要问题是以数字开头的字符串(但不是所有数字)将被转换为数字。这可以通过使用std::to_string
返回的数字并将其与原始字符串进行比较来轻松修复。