I am making a program that accepts input of name (max length of name is 100 characters, name can be one word, two words, and multiple words), and the date of birth of the person. You can focus on the name input only, the other code is just fine)
Here is my code
#include <stdio.h>
#include <string.h>
char ksg[] = "kosong";
struct database{
int urutan;
char nama[101]; //array that will contain the characters
int tanggal;
int bulan;
int tahun;
int umur;
} no[100];
int main()
{
int t;
scanf("%d", &t);
for(int i=0;i<t;i++){
scanf("%[^\n]s", no[i].nama); //This is the name input
scanf("%d/%d/%d",&no[i].tanggal, &no[i].bulan, &no[i].tahun);
}
for(int i=0;i<t;i++){
if(no[i].bulan>12){
strcpy(no[i].nama,ksg);
no[i].tanggal = 1;
no[i].bulan = 1;
no[i].tahun = 1;
no[i].umur = -1;
}
else if(no[i].bulan==1 ||no[i].bulan==3 ||no[i].bulan==5 ||no[i].bulan==7 ||no[i].bulan==8 ||no[i].bulan==10 ||no[i].bulan==12){
if(no[i].tanggal>31){
strcpy(no[i].nama,ksg);
no[i].tanggal = 1;
no[i].bulan = 1;
no[i].tahun = 1;
no[i].umur = -1;
}
}
else if(no[i].bulan==4 ||no[i].bulan==6 ||no[i].bulan==9 ||no[i].bulan==11){
if(no[i].tanggal>30){
strcpy(no[i].nama,ksg);
no[i].tanggal = 1;
no[i].bulan = 1;
no[i].tahun = 1;
no[i].umur = -1;
}
}
else if(no[i].bulan == 2 && no[i].tahun%4!=0){
if(no[i].tanggal>28){
strcpy(no[i].nama,ksg);
no[i].tanggal = 1;
no[i].bulan = 1;
no[i].tahun = 1;
no[i].umur = -1;
}
}
}
for(int i=0;i<t;i++){
if(no[i].umur!=-1){
no[i].umur = 2020-no[i].tahun;
}
}
for(int i=0;i<t;i++){
printf("Orang ke : %d\n", i+1);
printf("Nama: %s\n", no[i].nama); //This outputs the name
printf("TL : %d-%d-%d\n", no[i].tanggal, no[i].bulan, no[i].tahun);
if(no[i].umur==-1){
printf("Sepertinya ada kesalahan\n");
}
else{
printf("%d\n", no[i].umur-1);
}
}
return 0;
}
I already tried using
fgets(no[i].nama,100,stdin)
gets(no[i].nama)
scanf(%[^\n]s, no[i].nama)
And I have read a lot of solutions of similar questions, one which checks the newline character and trims it, one which was using getchar() after scanf.
Sample input and output :
input :
3
Hugo Broadway
21/1/1999
James Out
30/3/2000
Billy Bo
17/4/1997
expected output
Orang ke : 1
Nama: Hugo Broadway
TL : 21-1-1999
Umur: 19
Orang ke : 2
Nama: James Out
TL : 30-3-2000
Umur: 18
Orang ke : 3
Nama: Billy Bo
TL : 17-4-1997
Umur: 21
My output
Orang ke : 1
Nama:
TL : 0-0-0
Umur: 2019
Orang ke : 2
Nama: Hugo Broadway
TL : 21-1-1999
Umur: 20
Orang ke : 3
Nama:
TL : 0-0-0
Umur: 2019