1

I am trying to reading an input of the sort:

[Some text] (x,y)

where i need to store x,y in integers.

I tried this following code:

#include<iostream>
#include <cstdio>
using namespace std;

int main(){
    char temp[20];
    int x1, x2;
    scanf("%[^(]%d,%d)", temp, &x1, &x2);
    printf("%s %d %d", temp,x1,x2);
    return 0;
}

But the integers stored in x1 and x2 are always 0. This is the output i get:

this is a trial (8,6)
this is a trial  0 0

What is the error?

Nivetha
  • 698
  • 5
  • 17

4 Answers4

5
%[^(]%d,%d)

this tells scanf() to:

  1. Read all characters which aren't a left (opening) parenthesis;

  2. Then read a decimal integer,

  3. then read a comma,

  4. then read another decimal integer,

  5. then consume the trailing closing parenthesis.

What's missing is that after reading the leading text, you don't actually read the opening paren. So, either change your format string to include that:

%[^(](%d,%d)

Or, even better, consider parsing the string manually. scanf() format strings are obscure and it's easy to make one slight mistake and then the entire thing goes boom (as just happened to you). How about this instead?

char buf[LINE_MAX];
fgets(buf, sizeof(buf), stdin);
const char *lparen = strchr(buf, '(');
const char *comma = strchr(lparen + 1, ',');
// const char *rparen = strchr(comma + 1, ')'); // is this even needed?

char str[lparen - buf + 1];
memcpy(str, buf, lparen - buf);
str[lparen - buf] = 0;
int n1 = strtol(lparen + 1, NULL, 10);
int n2 = strtol(comma + 1, NULL, 10);

Some demo for goodness sake...

2

You forgot a paren (:

scanf("%[^(](%d,%d)", ...);
//          ^

After reading the not-(s you want to consume one before reading the ints.

EDIT as H2CO3 kindly mentioned: use fgets and strchr or sscanf, they are much safer

Community
  • 1
  • 1
Kninnug
  • 7,992
  • 1
  • 30
  • 42
  • 2
    And that's why `fgets()` and `strchr()` should be used instead of `scanf()`. –  Jun 14 '13 at 19:21
  • H2CO3 has kindly written an answer encouraging that as well :P –  Jun 14 '13 at 19:27
1

Because of the ( issue is occurring. You need to skip that character.

Use: scanf("%[^(](%d,%d)", temp, &x1, &x2);

Midhun MP
  • 103,496
  • 31
  • 153
  • 200
1

"%[^(]%d,%d)" ---> "%[^(](%d,%d)"

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70