在字符串向量中测试INT

Testing for int in a string vector

本文关键字:测试 INT 向量 字符串      更新时间:2023-10-16

我正在编写一个程序,其中我需要获得一个由字母组成的输入和两个数字,其中有两个空格。

我使用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]