在 C++ 中使用 sscanf 从字符串中提取一个 int

Using sscanf to extract an int from a string in C++

我的函数必须处理看起来像 say hello y(5) 或数据 |x(3)| 的字符串,我需要能够提取显示的整数并将其存储到一个名为地址的单独 int 变量中。然而,一些通过的字符串不会有任何整数,对于这些,地址必须默认为 0。当字符串包含整数时,它总是在括号之间。我曾尝试使用 sscanf,但是,作为 sscanf 的新手,我遇到了问题。出于某种原因,地址始终显示为 0。这是我的代码:

void process(string info)
{
int address = 0; // set to 0 in case info contains no digits
sscanf(info.c_str(), "%d", address);
.
.
.
// remainder of code makes other function calls using the address, etc
}

关于为什么 sscanf 找不到括号之间的整数的任何想法?谢谢!

link to a solution

int address;

sscanf(info.c_str(), "%*[^0-9]%d", &address);
printf("%d", address);

这应该提取括号之间的整数

why the sscanf fails to find the integer in between parentheses

sscanf(info.c_str(), "%d", address) 中的 "%d" 将导致 sscanf() 在检测到非数字序列后停止扫描。 "(5)" 之类的文本将在 "(" 处停止扫描。

相反,代码需要跳过非数字文本。


伪代码

  in a loop
    search for any of "-+0123456789"
    if not found return 0
    convert from that point using sscanf() or strtol()
    if that succeeds, return number
    else advance to next character

示例代码

int address;
const char *p = info.c_str();
for (;;) {
  p += strcspn(p, "0123456789+-");
  if (*p == 0) return 0;
  if (sscanf(p, "%d", &address) == 1) {
    return address;
  }
  p++;
}

备注:

strcspn 函数计算 s1 指向的字符串的最大初始段的长度,该字符串完全由不来自 s2 指向的字符串的字符组成。 C11 7.24.5.3 2


如果代码要依赖“它总是在括号之间。” 类似 "abc()def(123)" 的输入不会出现,它在 ().:

之间具有前面的非数字数据
const char *p = info.c_str();
int address;
if (sscanf(p, "%*[^(](%d", &address)==1) {
  return address;
}
return 0;

或干脆

int address = 0;
sscanf(info.c_str(), "%*[^(](%d", &address);
return address;

您可以使用像这样简单的方法,其中 strchr 找到第一次出现的“(”,然后使用 atoi return 将在第一个非数字处停止的整数。

  char s1[] = "hello y(5)";
  char s2[] = "data [x(3)]";
  char s3[] = "hello";

  int a1 = 0;
  int a2 = 0;
  int a3 = 0;

  char* tok = strchr( s1, '(');
  if (tok != NULL)
    a1 = atoi(tok+1);

  tok = strchr( s2, '(');
  if (tok != NULL)
    a2 = atoi(tok+1);

  tok = strchr(s3,'(');
  if (tok != NULL)
    a3 = atoi(tok+1);

  printf( "a1=%d, a2=%d, a3=%d", a1,a2,a3);

  return 0;

When a string contains an integer, it will always be in between parentheses

要严格遵守这个要求你可以试试:

void process(string info)
{
    int address;
    char c = '5'; //any value other than ) should work

    sscanf(info.c_str(), "%*[^(](%d%c", &address, &c);
    if(c != ')') address = 0;
    .
    .
    .
}