-1

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
grncds
  • 23
  • 4
  • Have you tried running your code line by line in a debugger while monitoring the values of all variables, in order to determine at which point your program stops behaving as intended? If you did not try this, then you may want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Andreas Wenzel May 21 '22 at 10:58
  • Try printing the values in the loop and you'll notice that it's not what you'd expect. See [`scanf("%c")` call seems to be skipped](https://stackoverflow.com/q/29775323/3049655) – Spikatrix May 21 '22 at 11:02

1 Answers1

0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335