0

I have this graph (with the first line is number of vertices, the following lines are directed edges):

9
1 4

1 5
2 5
4 5
4 6
6 9
7 6
7 8
8 9

There is no information to know how many edges are in the input so can anyone suggest a way to read this kind of input?

2
  • I tried while loop but I don't know when to stop the loop (I used scanf) Commented Nov 27, 2013 at 22:51
  • Also, remember that scanf returns the number of items successfully read in. Commented Nov 27, 2013 at 22:51

5 Answers 5

1

Thank you you all, I finally solved it, here is the input code:

while (1) {
    tmp1 = scanf("%d", &x);
    if (tmp1 == -1) // fix here
        break;
    tmp2 = scanf("%d", &y);

    new_vertex = (Vertex *) malloc(sizeof(Vertex));
    new_vertex->adj_vertex = NULL;
    new_vertex->vertex_no = y;
    new_vertex->time_stamp_visit = 0;
    new_vertex->time_stamp_finish = 0;

    last_vertex = getLastVertex((graph+x));
    last_vertex->adj_vertex = new_vertex;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Loop over this list from 1 to n-1 read the pair and insert the edge between these two nodes in your graph data structure.

Comments

0

I advise reading this: http://shygypsy.com/iotutorial.html

And using the method under "Read integers, one at a time, skipping whitespace, until the end of input."

In your code maintain state on whether it's a beginning or a ending vertice being inputted.

Don't forget to press ctrl+d when done typing input.

Comments

0

You can use a "termination character" that counts as EOF, like a -1 or something after the last pair of nodes.

Then your data would be:

9
1 4
1 5
2 5
4 5
4 6
6 9
7 6
7 8
8 9
-1

And your code:

while(1){
    scanf("%d %d", &num1, &num2);
    if(num1==-1) break;
    // process
}

Comments

0

I wrote getnum() to return an integer from stdin:

int getnum(int * last) {
    int c, n = 0;

    while ((c = getchar()) != EOF && 0x30 <= c && c < 0x40)
        n = n * 10 + (c - 0x30);

    if (last)
        *last = c;

    return n;
}

It will get digits from stdin until a non-digit character is retrieved. Because getnum() doesn't care what the non-digit character is, it doesn't matter how the numbers are arranged. They could all be on the same line, or in space-delimited pairs, one per line. I put this in a loop that stops once it reads in the right number of numbers, but you could easily loop until last pointed to non-whitespace.

Additionally, if you want to read from a FILE or fd (integer file descriptor), pass the FILE/fd to getnum() and use getc(FILE *)/fgetc(int).

1 Comment

scanf is a much easier way to do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.