Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | James Kuyper <jameskuyper@verizon.net> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: question about scanf |
| Date | 2014-04-16 18:15 -0400 |
| Organization | Self |
| Message-ID | <534F00E9.3050409@verizon.net> (permalink) |
| References | <40832b-tro.ln1@rama.universe> |
On 04/16/2014 03:06 PM, TP wrote:
> Hi everybody,
>
> I want to scan a string for an integer, but I don't want any other character
> in the string after the integer, otherwise an error has to be raised.
>
> I have scrutinized the manual page of scanf, the best solution I have found
> is something as:
>
> //////////////////
> #include <stdio.h>
>
> int main( void )
> {
> int occurrence;
> int nbcharreadjustafteroccurrence;
> int nbcharreadatendofthestring;
>
> printf("assignement number=%i\n"
> , sscanf( "foo 3bar", "foo %d%n%*s%n"
> , &occurrence
> , &nbcharreadjustafteroccurrence
> , &nbcharreadatendofthestring ) );
>
> printf("characters after assignment=%i\n"
> , nbcharreadatendofthestring - nbcharreadjustafteroccurrence );
>
> return 0;
> }
>
> //////////////////
>
> $ ./a.out
> assignement number=1
> characters after assignment=3
> $
>
> So I can raise an error if the number of characters is greater than zero.
> Is there any better solution?
"raise an error" is not very clear, and your example program doesn't
clarify it. I'll just print a message "Error raised", and you can insert
the appropriate code in place of that message:
include <stdio.h>
#include <string.h>
int main( void )
{
int occurrence;
int nbcharreadjustafteroccurrence;
char string[] = "foo 3bar";
printf("assignment number=%i\n"
, sscanf(string, "foo %d%n"
, &occurrence
, &nbcharreadjustafteroccurrence));
if(string[nbcharreadjustafteroccurrence])
{
printf("Error raised\n");
}
printf("characters after assignment=%zu\n"
, strlen(string+nbcharreadjustafteroccurrence));
return 0;
}
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
question about scanf TP <TP@frenoespam.fr.invalid> - 2014-04-16 21:06 +0200
Re: question about scanf Kaz Kylheku <kaz@kylheku.com> - 2014-04-16 21:38 +0000
Re: question about scanf Ben Bacarisse <ben.usenet@bsb.me.uk> - 2014-04-16 22:59 +0100
Re: question about scanf TP <TP@frenoespam.fr.invalid> - 2014-04-21 08:01 +0200
Re: question about scanf James Kuyper <jameskuyper@verizon.net> - 2014-04-16 18:15 -0400
Re: question about scanf "Bill Cunningham" <nospam@nspam.invalid> - 2014-04-20 09:47 -0400
Re: question about scanf viju.kantah@gmail.com - 2014-04-20 07:04 -0700
Re: question about scanf gazelle@shell.xmission.com (Kenny McCormack) - 2014-04-20 15:24 +0000
Re: question about scanf "BartC" <bc@freeuk.com> - 2014-04-20 17:10 +0100
csiph-web