0

I am getting the following string as input from the user: "id,name,age,grade,country,city"

-id consists of digits 0-9 only -name consists of a-zA-z letters -grade consists of digits 0-9 only -country consists of a-zA-z letters, white spaces and '-' dashes. -city consists of a-zA-z letters, white spaces and '-' dashes.

I am trying to speharete each field into its own string.

my code is:

char id[MAX_STRING_SIZE], name[MAX_STRING_SIZE], grade[MAX_STRING_SIZE], age[MAX_STRING_SIZE],
                    country[MAX_STRING_SIZE],city[MAX_STRING_SIZE];

sscanf(userInput,SEPARATOR,id,name,grade,age,country,city);

where userInput is a string in the form "id,name,age,grade,country,city"

and const char SEPARATOR[] = "%[^,],%[^,],%[^,],%[^,],%[^,\n],%s";

however, this code breaks with certain inputs, such as "id,,age,grade,country,city"

11
  • 1
    And why is that a problem? Thats an invalid input. Just check sscanf return value and issue an error message if the input is invlaid. Commented Apr 9, 2020 at 14:00
  • 1
    Why are you doing this? If you already have the string, there's (probably) no need to make additional copies of all the data. Just parse the string! Iterate over the string and look for commas (or use strchr), replace them with '\0', and set the pointer. Or even use strtok. Using strtok is usually a mistake, but it's better than the using sscanf for this. Commented Apr 9, 2020 at 14:02
  • @Eraklon because I need to know in which field I have a problem.. your solution is not going to work Commented Apr 9, 2020 at 14:07
  • @WilliamPursell scanning char by char? that hell of alot of code to write! Commented Apr 9, 2020 at 14:07
  • @willhunting1337 Then it would be wise to phrase the question in a way so it is clear what exactly you want. What is your expected output/behaviour for the invalid input. Commented Apr 9, 2020 at 14:10

1 Answer 1

1

Here's something you could do instead of sscanf, as suggested by @WilliamPursell

char* field[6];
field[0] = userInput;

for (int n=0, i=1; userInput[n] && (i < sizeof(field)/sizeof(field[0])); ++n)
{
    if (userInput[n] == ',')
    {
        userInput[n] = '\0';
        field[i] = &userInput[n+1];
        ++i;
    }
}

It might be necessary to make a copy of userInput first

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.