简体   繁体   中英

simple program to get and display name and dob of friend what is the error

The program tells to take input name and dob from friend and display it using structures.

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    struct friend {
        char name[40];
        int dd, mm, y;

    } f;
    printf("enter details");
    scanf("%c %d %d %d", &f.name, &f.dd, &f.mm, &f.y);
    printf("name is %c and dob is %d/%d/%d", f.name, f.dd, f.mm, f.y);
}

OUTPUT:

enter details dasd 10 10 2004
name is £ and dob is 0/35/11408852

the output is giving this garbage value why?

You should correct these issues:

  • to read a word, you should use %s in scanf or more precisely %39s to read a word of up to 39 characters and a null terminator. %c reads a single character.
  • to check that input was complete, compare the return value of scanf to 4, the expected number of successful conversions. As coded, scanf() will fail to convert the DoB if the name has more than 1 letter, hence the members dd , mm and y remain uninitialized, a potential explanation for the garbage output.
  • to print the string in the name array, use %s in printf . %c expects an int and you pass an array or char , which is passed as a pointer to its first element. This has undefined behavior, another explanation for garbage output.

Here is a modified version:

#include <stdio.h>

int main() {
    struct friend {
        char name[40];
        int dd, mm, yy;
    } f;
    printf("enter details: ");
    if (scanf("%39s %d %d %d", f.name, &f.dd, &f.mm, &f.yy) == 4) {
        printf("name is %s and dob is %d/%d/%d\n", f.name, f.dd, f.mm, f.yy);
    } else {
        printf("invalid or missing input\n");
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM