Malcolm McLean wrote:
>
Here is a handy hint to extract the length
of input consumed by scanf().
(Returns -1 on a bad match / memory failure).
static int int_sscanf(const char *src, const char *fmt)
{
char *fmt2;
int i;
int j =0;
int answer = -1;
fmt = malloc(strlen(fmt) * 2 + 3);
if(!fmt)
return -1;
for(i=0;fmt[i];i++)
{
if(fmt[i] == '%')
{
if(fmt[i+1] == '%')
{
fmt2[j++] = '%';
fmt2[j++] = '%';
i++;
}
else if(fmt[i+1] == '*')
{
fmt2[j++] = '%';
fmt2[j++] = '*';
i++;
}
else
{
fmt2[j++] = '%';
fmt2[j++] = '*';
}
}
fmt2[j++] = fmt[i];
}
fmt2[j++] = '%';
fmt2[j++] = 'n';
fmt2[j++] = 0;
sscanf(src, fmt2, &answer);
free(fmt2);
return answer;
}
I can't figure out how to use it.
This program crashes on the int_sscanf function call.
/* BEGIN int_sscanf.c */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int int_sscanf(const char *src, const char *fmt);
int main(void)
{
const char src[] = "INT_MAX";
const char *fmt = "%s";
char dest[sizeof src];
int rc;
rc = sscanf(src, fmt, dest);
printf("rc is %d\n", rc);
puts(dest);
rc = int_sscanf(src, fmt);
printf("rc is %d\n", rc);
return 0;
}
static int int_sscanf(const char *src, const char *fmt)
{
char *fmt2;
int i;
int j =0;
int answer = -1;
fmt = malloc(strlen(fmt) * 2 + 3);
if(!fmt)
return -1;
for(i=0;fmt[i];i++)
{
if(fmt[i] == '%')
{
if(fmt[i+1] == '%')
{
fmt2[j++] = '%';
fmt2[j++] = '%';
i++;
}
else if(fmt[i+1] == '*')
{
fmt2[j++] = '%';
fmt2[j++] = '*';
i++;
}
else
{
fmt2[j++] = '%';
fmt2[j++] = '*';
}
}
fmt2[j++] = fmt[i];
}
fmt2[j++] = '%';
fmt2[j++] = 'n';
fmt2[j++] = 0;
sscanf(src, fmt2, &answer);
free(fmt2);
return answer;
}
/* END int_sscanf.c */
--
pete