Struggling with printing the details of the struct

50 Views Asked by At

I have included a 'main.h' file in this program, the code of which I am providing below.

#ifndef MAIN_H
#define MAIN_H

//constant directives
#define MAX_FLIGHTS 5
#define MAX_CODE 5

//structure declarations
typedef struct flight_data{
    char flight_number[MAX_CODE];
    char destination[100];
    char timings[5];
}f_data;

//function declarations

#endif

And below is the main program file which is 'main.c'.

#include <stdio.h>
#include <stdlib.h>
#include "main.h"

f_data flight_log[MAX_FLIGHTS] = {
    {"AI123", "Mumbai", "18:03"},
    {"AA901", "Panaji", "13:45"},
    {"ID111", "New Delhi", "14:00"},
    {"FE102", "Dubai", "21:20"},
    {"FE103", "Sharjah", "22:40"}
};

int main(int argc, char *argv[]){
    while(1){
        char user_prompt;
        printf("Enter 'C' to exit.\n");
        printf("Enter 'v' to view the flight log.\n>>>");
        scanf(" %c", &user_prompt);

        if(user_prompt == 'C' || user_prompt == 'c'){
            printf("Program terminated");
            return 0;
        }
        else if(user_prompt == 'v' || user_prompt == 'V'){
            printf("These are the current flight logs\n");
            for(int i = 0; i < MAX_FLIGHTS; i++){
                printf("%d. %s\t%s\t%s\n", i+1, flight_log[i].flight_number, flight_log[i].destination, flight_log[i].timings);
            }
        }
        else{
            printf("Error : Invalid argument entered.\n");
            return EXIT_FAILURE;
        }
    }
    return EXIT_SUCCESS;
}

I expected it to print the output like:

  1. AI123 Mumbai 18:03

But, it is printing something like this:

These are the current flight logs
1. AI123Mumbai  Mumbai  18:03AA901Panaji
2. AA901Panaji  Panaji  13:45ID111New Delhi
3. ID111New Delhi       New Delhi       14:00FE102Dubai
4. FE102Dubai   Dubai   21:20FE103Sharjah
5. FE103Sharjah Sharjah 22:40

This output is not what I expected as it is also printing the flight number and destination of the next flight in the same line.

1

There are 1 best solutions below

0
On

Don't forget to reserve space for the null character when you define a string! Otherwise the string is not properly terminated and a print function will not know where the string ends.

#ifndef MAIN_H
#define MAIN_H

//constant directives
#define MAX_FLIGHTS 5
#define MAX_CODE 6

//structure declarations
typedef struct flight_data{
    char flight_number[MAX_CODE];
    char destination[100];
    char timings[6];
}f_data;

//function declarations

#endif