Scanning Multiple inputs from one line using scanf

You have your printing loop inside your reading loop. It is trying to print out all of the trip information after reading the first one in.

Edit: The trouble here is that the way scanf handles single characters is kinda unintuitive next to the way it handles strings and numbers. It reads the very next character from standard in, which is probably a newline character from when you finished typing the previous input. Then it proceeds to try and read an integer, but instead it finds the letter you had intended to be consumed by the %c. This causes scanf to fail and not initialize stop_num.

One way around this may be to read in a string instead. scanf will start reading the string at the first non-whitespace character and stop reading it at the first whitespace character. Then just take the first character from the buffer you read the string into.

#include <stdio.h>

#define MAX 3
#define MAXTRIP 6

struct stop {
    float cost;
    float time;
};

struct trip {
    char Dest_letter;
    int stop_num;
    struct stop leg[MAX];
};

int main(void)
{
    int trip_num, index, i;
    struct trip travel[MAXTRIP];
    char buffer[10];

    printf("Enter number of trips: ");
    scanf("%d", &trip_num);
    for (index = 0; index < trip_num; index++) {
        printf("Please enter destination letter/number of stops:\n");
        scanf("%s %d", buffer, &travel[index].stop_num);
        travel[index].Dest_letter = buffer[0];
        for (i = 0; i < travel[index].stop_num; i++){
            printf("Please enter cost/length of stop %d:\n", i);
            scanf("%f %f", &travel[index].leg[i].cost, &travel[index].leg[i].time);
        }
    }
    printf("%d trips\n", trip_num);
    for (index = 0; index < trip_num; index++) {

Leave a Comment