-2

Suppose I have an input like this, one cell each line:

[0,0]
[0,2]
[0,4]
[2,4]
[4,4]

I've managed to read them one by one using something like [%d,%d] and get the output like:

cell1: row: 0, col:0
cell1: row: 0, col:2

then I have another input like this

[0,0]->[0,1]->
[0,2]->[0,3]->
[0,4]->[1,4]->
[2,4]->[3,4]->
[4,4]->[5,4]

How do I read the input without being interrupted by the arrow '->'?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 2
    Post the code you've tried to use to parse the `[]->...` format. – Andrew Henle Oct 18 '19 at 11:14
  • 1
    I guess the `[%d,%d]` is supposed to be a `scanf` format. Please [edit] your question and add a small program that demonstrates how you read the input and print the output for the first input example. – Bodo Oct 18 '19 at 11:16

3 Answers3

5

Okay, quick and cheap solution: Scan everything up to an opening bracket and don't care what it is. Then scan the actual data. Repeat.

int x, y;

scanf("%*[^[]");            // ignore everything up to the first [

while (scanf(" [%d ,%d]", &x, &y) == 2) {
    printf("[%d, %d]\n", x, y);

    scanf("%*[^[]");        // ignore stuff between ] and [
}
M Oehm
  • 28,726
  • 3
  • 31
  • 42
0
"[%d,%d]->"

Use one whitespace in your format string to skip any number of whitespace (including newline...) in your input.

DevSolar
  • 67,862
  • 21
  • 134
  • 209
0

If I understand you correctly, you have input lines like

[0,0]
[0,2]
[0,4]

and you are successfully reading them using a fscanf call like

fscanf(ifp, " [%d,%d]", &row, &col);

If that's so, and if you have another input format

[0,0]->[0,1]->
[0,2]->[0,3]->
[0,4]->[1,4]->

why can't you just use something like

fscanf(ifp, " [%d,%d]->[%d,%d]->", &row1, &col1, &row2, &col2);

I suppose you could also use

fscanf(ifp, " [%d,%d]->", &row, &col);

which would require two calls to read each line.

P.S. Obligatory scanf reminders:

  1. Remember to always check the return value from scanf and fscanf to make sure the expected inputs were matched. (I conspicuously failed to follow this advice in the code fragments in this answer.)

  2. Even though it often seems like the thing to use, fscanf is usually a poor tool for the job, and it can be more trouble than it's worth to get it do do what you actually want. You can consider using alternatives.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103