Page 1 of 1
about using "sscanf" :=)
Posted: Sun Jul 06, 2003 4:54 pm
by hank
[c]#include <stdio.h>
#include <string.h>
void main()
{
char arr[80];
int i,j,k;
strcpy(arr,"1 2 3");
sscanf(arr,"%d",&i);
sscanf(arr,"%d",&j);
sscanf(arr,"%d",&k);
printf("( %d %d %d )",i,j,k);
}[/c]
Can you tell me why "j != 2" and "k != 3" ?
I want to convert the string "arr" to int ?
How to modify my code?
Posted: Sun Jul 06, 2003 7:04 pm
by Adil
hi. i would use the following code:
[c]#include <stdio.h>
#include <string.h>
void main()
{
char arr[80];
int i,j,k;
strcpy(arr, "1 2 3");
sscanf(arr, "%d %[^\0]", &i, arr);
sscanf(arr, "%d %[^\0]", &j, arr);
sscanf(arr, "%d %[^\0]", &k, arr);
printf("(%d %d %d)\n", i, j, k);
}
[/c]
in your example, when you take the first input (i) from the string, the string itself (arr) is never changing. so whenever you take another input (j) from the same string (arr) , they (i and j) will be the same.
i think i saw in some post someone mentioned that this can be done in an easier way by using something like strstream in C++.
Posted: Mon Jul 07, 2003 6:23 am
by hank
Thanks a lot!!but what's the meaning of "%[^\0]"?

Posted: Mon Jul 07, 2003 8:54 am
by Dominik Michniewski
or when you use strtok() in C
Best regards
DM
Posted: Fri Jul 11, 2003 12:49 pm
by Julien Cornebise
hank wrote:Thanks a lot!!but what's the meaning of "%[^\0]"?

%[^\0] means "take all character until you find \0". It's a bit like %s, but %s stops when it finds a space or a new line. %s is equivalent to %[^ \n\r].
With that trick, you read a %d from attr, then you read the end of attr and store it IN ATTR, and as a consequence when you'll next read "%d" from attr, you'll get "2", not "1" again.
PS to Adil : are you sure one could never have a trouble, reading from attr and writing to it anew, on certain operating systems ? Wouldn't it be safer (though slower) to read to a temporary buffer, then to strcpy ?
Posted: Fri Jun 03, 2005 12:02 pm
by jakabjr
actually, "%s" skips all preceeding blank spaces (specified in isspace() for instance), which are more then " ", "\n" and "\r". (the tab is a blank surely "\t").
as for reding from a string, here's a good topic, which gives u all the solutions u need:
http://acm.uva.es/board/viewtopic.php?t ... 431b7e32aa