c - 使用 sscanf 迭代

标签 c getline scanf

我对 sscanf 函数了解不多,但我想做的是迭代一行整数。给定变量

    char *lineOfInts

我已将其作为注册用户输入的行。我能够很好地获得输入,但是当我尝试使用 sscanf 时,我想迭代每个 int。我知道如果我知道之前会有多少个整数,我就可以计算出所有的整数。

   sscanf(lineOfInts, "%d %d %d..etc", &i, &j, &k...) 

但是如果我不知道用户将输入多少个整数怎么办?如何仅用一个变量来解释所有整数?喜欢

   sscanf(lineOfInts, "%d", &temp);
   //modifying int
   // jump to next int and repeat

谢谢!

最佳答案

也许是这样的:

#include <stdio.h>

int main(void)
{
  const char * str = "10 202 3215 1";
  int i = 0;
  unsigned int count = 0, tmp = 0;
  printf("%s\n", str);
  while (sscanf(&str[count], "%d %n", &i, &tmp) != EOF) {
    count += tmp;
    printf("number %d\n", i);
  }

  return 0;
}  

关于c - 使用 sscanf 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32860697/

相关文章:

c - scanf() 将换行符留在缓冲区中

c - 什么时候使用 &?

c - 选择始终返回数据

c++ - C/C++ : goto into the for loop

c++ - getline(cin,input) 多行? (C++)

C 将大文件读入 char* 数组太慢

c - 在 C 中读取十六进制文件

C:当从数组引用时,我的结构的属性不会改变?

c - C99 中与调整参数相关的未定义行为

c - 使用 stdin 读取单列数据文件并使用 C 中的函数值返回值