user2805451
user2805451

Reputation: 23

Get input separated by commas

I need to make a program that asks the user for input (until they terminate it by typing exit). The input is separated by commas (example: value,value,value). Each separate value then needs to be put into its own variable.

Example:

If the user types in hello,15,bye, I need to put hello into the first variable, 15 into the second variable, and bye into the third variable.

Here's what I have so far:

int main(void) {
  char input[100];
  char first[100];
  char second[100];
  char third[100];

  printf("Enter commands: ");

  while(fgets(input, 100, stdin)) {
    if(strncmp("exit", input, 4) == 0) {
      exit(0);
    }

    // missing code
  }
}

How would I separate the input by the commas and add the values into their own variables?

Upvotes: 2

Views: 1399

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754520

Use sscanf() and scan sets:

if (sscanf(input, "%99[^,],%99[^,],%99[^,\n]", first, second, third) != 3)
    ...oops...

The 99's appear because the strings are defined as 100, and this ensures no overflow, though with the input line also being 100, overflow isn't a problem.

Two of the scan sets are %99[^,] which looks like a limited form of regular expression; the caret means 'negated scan set', and therefore the string matches anything except a comma. The last is %99[^,\n] which excludes newlines as well as commas.

You can skip leading white spaces on the names by adding spaces before the conversion specifications. Trailing white spaces can't readily be avoided; if they're a problem, remove them after the conversion is successful.

Upvotes: 4

Related Questions