As you don't know how many value pairs the user will enter you have to use a loop.
After a successful sscanf
you can search for a closing parenthesis ')'
and start the next sscanf
from the position after it.
To avoid an error message in case of additional spaces between or after the data I added code to skip whitespace and changed the format string to be more flexible.
I use a function for skipping space and checki9ng for end-of-string because I need it at two places.
Edit:
As shown in the answer to a similar question How to use sscanf in loops? you can get the offset to the next position directly from sscanf
using the %n
format specifier, so the strchr
is not necessary. I won't change this answer here. See the other question and adapt the code accordingly.
(There are more ways to solve this problem.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* skip whitespace and check for end of string */
int skip_space(char **pos)
{
while(isspace(**pos))
{
(*pos)++;
}
return (**pos == '\0');
}
int main()
{
char str[1024];
char *pos;
int key,value;
printf("enter key-value pairs of integer numbers like (a,b)(c,d): ");
while (fgets(str,sizeof(str),stdin)!=NULL)//stop read files when reached end of the line
{
pos = str;
if(skip_space(&pos))
{
break;
}
do
{
/* added spaces to format string for more flexibility */
if(sscanf(pos," (%d , %d )",&key, &value) == 2)// if the function can address both number
{
//InsertNode(AVLtree,key,value);
printf("%d, %d\n", key,value);
}
else
{
printf("cannot get correct key & Value at position %d: %s\n", (int)(pos - str), pos);
exit(1);
}
/* since scanf was successful we must have a ')' in the input, so NULL should not occur */
pos = strchr(pos, ')');
/* skip ')' */
pos++;
} while(skip_space(&pos) == 0);
}
return 0;
}
Result:
enter key-value pairs of integer numbers like (a,b)(c,d): (1,2) ( 3 , 4 ) (5,6)(7.0,8)
1, 2
3, 4
5, 6
cannot get correct key & Value at position 21: (7.0,8)
enter key-value pairs of integer numbers like (a,b)(c,d): (1,2) ( 3 , 4 ) (5,6)
1, 2
3, 4
5, 6
(7,8)
7, 8
Unrelated error: if(*str == "\n")
is wrong.
If you want to check for a newline character at the beginning of the string, use
if(*str == '\n')
If you want to check if the whole string is equal to a string that consists of a single newline, use
if(strcmp(str, "\n") == 0)
or simplified
if(!strcmp(str, "\n"))