How To sscanf() Example Using a Comma (,) as Delimiter

已淘汰的 KB 內容免責聲明

本文章所撰寫之相關產品,Microsoft 已不再提供支援。 因此,本文章將以「現狀」提供,並且將不再更新。

Summary


The example below shows how to use the sscanf() C run-time function to read from an internal buffer delimiting fields with a comma (,). The key is to use the brackets in the format of sscanf() function. The format will be %[^','], which tells the function to read from the buffer until a comma (,) is reached.

Sample Code

/* The following sample illustrates the use of brackets and the
caret (^) with sscanf().
Compile options needed: none
*/

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

char *tokenstring = "first,25.5,second,15";
int result, i;
double fp;
char o[10], f[10], s[10], t[10];

void main()
{
result = sscanf(tokenstring, "%[^','],%[^','],%[^','],%s", o, s, t, f);
fp = atof(s);
i = atoi(f);
printf("%s\n %lf\n %s\n %d\n", o, fp, t, i);
}
內容

文章識別碼:38335 - 最後檢閱時間:2014年6月17日 - 修訂: 1

意見反應