0

使用istringstream,我们可以从字符串中一个一个地读取项目,例如:

istringstream iss("1 2 3 4");
int tmp;
while (iss >> tmp) {
    printf("%d \n", tmp);  // output: 1 2 3 4
}

我们可以这样做sscanf吗?

4

2 回答 2

2

如果您可以使用strtok将字符串分成单独的标记

  char str[] ="1 2 3 4";
  char * pch;
  pch = strtok (str," ");
  while (pch != NULL)
  {
    int tmp;
    sscanf( pch, "%d", &tmp );
    printf( "%d \n", tmp );
    pch = strtok (NULL, " ");
  }

否则,scanf 支持 %n 转换,它可以让您计算到目前为止消耗的字符数(我还没有测试过,可能存在我没有考虑过的陷阱);

  char str[] ="1 2 3 4";
  int ofs = 0;
  while ( ofs < strlen(str) )
  {
    int tmp, ofs2;
    sscanf( &str[ofs], "%d %n", &tmp, &ofs2 );
    printf( "%d \n", tmp );
    ofs += ofs2;
  }
于 2014-11-15T03:20:42.347 回答
2

你可以用这个相当接近地模拟它

const char *s = "1 2 3 4";
int tmp, cnt;

for (const char *p = s; sscanf(p, "%d%n", &tmp, &cnt) == 1; p += cnt)
  printf("%d\n", tmp);
于 2014-11-15T03:29:19.777 回答