测试字符串向量中的 int

Testing for int in a string vector

我正在编写一个程序,我需要获取一行输入,其中包含一个字母和两个数字,在 between.Let 中带有 spaces,例如 [=16] =].

我使用 std::getline 将输入作为字符串输入,因此空白 space 不会有任何问题,然后使用 for 循环浏览字符串中的各个字符。仅当第 2 个和第 3 个字符(第 3 个和第 5 个计算空格)是数字时,我才需要执行特定条件。

如何测试字符串中某个位置的字符是否为整型?

为了您的目的,我会将该行放入 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
}

它有一个函数isdigit()

要检查字符串的第 2 个和第 3 个字符 s,您可以使用此代码:

if (isdigit(s[2]) && isdigit(s[3]))
{
  // both characters are digits
}

但在您的情况下 (s == "I 5 6"),您似乎需要检查 s[2]s[4]

您可以使用 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 alphabetic\n",str[i]);
    else printf ("character %c is not alphabetic\n",str[i]);
    i++;
  }
  return 0;
}

isalpha 检查 c 是否为字母。 http://www.cplusplus.com/reference/cctype/isalpha/

输出将是:

character C is alphabetic character + is not alphabetic character + is not alphabetic

对于数字使用 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;
}

输出将是:

The year that followed 1776 was 1777

isdigit 检查c是否为十进制数字字符。 http://www.cplusplus.com/reference/cctype/isdigit/