当我使用 getline
时,我会输入一堆字符串或数字,但我只希望 while 循环输出不是数字的单词".那么有没有办法检查单词"是否是数字?我知道我可以使用 atoi()
C-strings 但是对于 string 类的字符串呢?
When I use getline
, I would input a bunch of strings or numbers, but I only want the while loop to output the "word" if it is not a number.
So is there any way to check if "word" is a number or not? I know I could use atoi()
for
C-strings but how about for strings of the string class?
int main () {
stringstream ss (stringstream::in | stringstream::out);
string word;
string str;
getline(cin,str);
ss<<str;
while(ss>>word)
{
//if( )
cout<<word<<endl;
}
}
另一个版本...
使用strtol
,包裹起来在一个简单的函数中隐藏其复杂性:
Use strtol
, wrapping it inside a simple function to hide its complexity :
inline bool isInteger(const std::string & s)
{
if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false;
char * p;
strtol(s.c_str(), &p, 10);
return (*p == 0);
}
strtol
?就我喜欢 C++ 而言,有时 C API 是最好的答案:
strtol
?As far as I love C++, sometimes the C API is the best answer as far as I am concerned:
strtol
乍一看似乎很原始,因此解释将使代码更易于阅读:
strtol
seems quite raw at first glance, so an explanation will make the code simpler to read :
strtol
将解析字符串,在第一个不能被视为整数一部分的字符处停止.如果您提供 p
(就像我上面所做的那样),它会将 p
设置在第一个非整数字符处.
strtol
will parse the string, stopping at the first character that cannot be considered part of an integer. If you provide p
(as I did above), it sets p
right at this first non-integer character.
我的推理是,如果p
没有设置为字符串的结尾(0字符),那么字符串s
中就有一个非整数字符,这意味着 s
不是一个正确的整数.
My reasoning is that if p
is not set to the end of the string (the 0 character), then there is a non-integer character in the string s
, meaning s
is not a correct integer.
第一个测试是为了消除极端情况(前导空格、空字符串等).
The first tests are there to eliminate corner cases (leading spaces, empty string, etc.).
当然,这个函数应该根据您的需要进行定制(前导空格是否有错误?等).
This function should be, of course, customized to your needs (are leading spaces an error? etc.).
查看 strtol
的描述:http://en.cppreference.com/w/cpp/string/byte/strtol.
另请参阅strtol
的姐妹函数(strtod
、strtoul
等)的说明.
See, too, the description of strtol
's sister functions (strtod
, strtoul
, etc.).
这篇关于如何检查 C++ 字符串是否为 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!