Search code examples
arrayscloopscharscanf

C for loop suddenly stops


I'm trying to read distance between two nodes in a Graph and store it in an array but the loop doesn't work as expected. It suddenly stops.

Output:
Edge Number: 4
Enter distance between two nodes, Example: A B 10 
A C 3
A B 2
C B 2

...Program finished with exit code 0
Press ENTER to exit console.

For example, when edgeNumber is 4, it stops at 3. Here's my code. Thanks in advance.

Code:

#include <stdio.h>
#define S 50

int main(){
    
    int  dist[S][S], edgeNumber, i, temp;
    char node1, node2;
    
    
    printf("Edge Number: ");
    scanf("%d", &edgeNumber);
    
    
    printf("Enter distance between two nodes, Example: A B 10 \n");
    for(i = 0; i < edgeNumber; i++){
        scanf("%c %c %d", &node1, &node2, &temp);
        dist[((int)node1) - 65][((int)node2) - 65] = temp;
        dist[((int)node2) - 65][((int)node1) - 65] = temp;
    }
    
    return 0;
}

Solution

  • Just rewrite this call of scanf

    scanf("%c %c %d", &node1, &node2, &temp);
          ^^^
    

    like

    scanf( " %c %c %d", &node1, &node2, &temp);
           ^^^
    

    The leading space in the format string allows to skip white space characters in the input buffer including the new line character '\n'.

    Also it is a bad idea to use magic numbers like 65. And you should check entered characters that they are letters and convert them to upper case. Otherwise your code is very unsafe. Also you should test the result of calls of scanf.