Reading a string in C until a "," is encountered

Viewed 66

I took an assigment today where i had to read some strings with "," between them for example :John , mike,Kate. I have tried to you scanf("%s[^,]", string) but it would not work and all I did was reading all text like a whole string . I want those words to be different strings not one.

1 Answers

You were so close. You have used the %s format specifier when what you wanted was the %[^...] format specifier. See the "Negated scanset."

scanf("%[^,]", string);

You may also wish to use a width specifier to prevent overflows.

#include <stdio.h>

int main(void) {
  char foo[100] = {0};

  scanf("%99[^,]", foo);

  printf("%s\n", foo);

  return 0;
}

Additionally, you should get in the habit of checking the return value of scanf to ensure it was successful. scanf will return the number of items scanned. In this case we can check that it is 1.

#include <stdio.h>

int main(void) {
  char foo[100] = {0};

  if (scanf("%*[^,]", 99, foo) != 1) {
    printf("Error reading.\n");
    return 1;
  }

  printf("%s\n", foo);

  return 0;
}

To read multiple names separated by commas, you'll need to do a little more work, reading an entire line, then tokenizing it. You may find getline and strtok useful for this work.

Related