Home > Back-end >  Reading a string in C until a "," is encountered
Reading a string in C until a "," is encountered

Time:09-06

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.

CodePudding user response:

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("           
  •  Tags:  
  • c
  • Related