在字符串向量中测试INT
Testing for int in a string vector
我正在编写一个程序,其中我需要获得一个由字母组成的输入和两个数字,其中有两个空格。
我使用std :: getline作为字符串获取输入,因此空白空间不会有任何问题,然后是一个用于浏览字符串中各个字符的循环。我需要某个条件才能执行仅当第二个字符和第三个字符(第3和第5个计数空白)是数字。
如何测试字符串中某个位置的字符是否是int?
出于您的目的,我将线路放入std::istringstream
并使用普通流提取操作员从中获取值。
也许像
char c;
int i1, i2;
std::istringstream oss(line); // line is the std::string you read into with std::getline
if (oss >> c >> i1 >> i2)
{
// All read perfectly fine
}
else
{
// There was an error parsing the input
}
您可以使用isalpha
。这是一个示例:
/* isalpha example */
#include <stdio.h>
#include <ctype.h>
int main ()
{
int i=0;
char str[]="C++";
while (str[i])
{
if (isalpha(str[i])) printf ("character %c is alphabeticn",str[i]);
else printf ("character %c is not alphabeticn",str[i]);
i++;
}
return 0;
}
isalpha
检查C是否是字母字母。http://www.cplusplus.com/reference/cctype/isalpha/
输出将是:
字符c是字母字符 不是 字母字符 不是字母
和数字使用isdigit
:
/* isdigit example */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
char str[]="1776ad";
int year;
if (isdigit(str[0]))
{
year = atoi (str);
printf ("The year that followed %d was %d.n",year,year+1);
}
return 0;
}
输出将是:
1776年之后的一年是1777年
isdigit
检查C是否是十进制数字字符。http://www.cplusplus.com/reference/cctype/isdigit/
有一个功能isdigit()
:
要检查字符串s
的第二和第三个字符,您可以使用此代码:
if (isdigit(s[2]) && isdigit(s[3]))
{
// both characters are digits
}
但是,在您的情况下(s == "I 5 6"
),似乎您需要检查s[2]
和s[4]
。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 谷歌测试编译错误 Os X:函数式转换从"int"到"internal::FloatingEq2Matcher"的模糊转换<float>
- 单元测试 - 仅在"int main()"左右重新编译以减少编译时间
- 在字符串向量中测试INT
- 如何使用 <int, int> 和 <string, int> 等模板测试给定的 ADT 实现?
- 为什么在我的测试程序中,从字符缓冲区读取一个int时,"std::copy"5x(!)比"
- 如何测试输入是字符串还是int
- C++1z 处理 == 测试,在自动函数中使用 std::initializer_list<int> 和 w/o const
- 如果int是数字c++,则测试将其转换为char
- 无法将向量<int>转换为 int* 用于布尔测试密码
- 从Find Max方法返回一个int值并将其打印在测试文件中
- 将int转换为字节并编写相应的测试方法