如何读取格式为"123 35 123 0 0 0 817"的C中的数据

Fei*_*Xue 2 c io

我想从字符串中读取数据.字符串是这样的:

"123 35   123 0    0      0       817 0    0   0   0"
Run Code Online (Sandbox Code Playgroud)

字符串中有一些不确定的数字和空格.我想读第三个数字.如何读取数据?

unw*_*ind 10

使用sscanf().它将跳过空格.

int a, b, c;
if( sscanf(string, "%d %d %d", &a, &b, &c) == 3)
  printf("the third number is %d\n", c);
Run Code Online (Sandbox Code Playgroud)

您还可以使用%*来禁止分配两个第一个数字:

int a;
if( sscanf(string, "%*d %*d %d", &a) == 1)
  printf("the third number is %d\n", a);
Run Code Online (Sandbox Code Playgroud)

请注意,它sscanf()返回它所做的成功转换(和赋值)的次数,这就是在依赖输出变量的值之前必须检查返回值的原因.

  • @ RichardJ.RossIII平心而论,Stack Overflow可能没有提醒你已经发布了你的答案 - 这个功能不是即时的. (2认同)