I am just into coding... I started with C language. Today when I was solving a code problem. Problem was to display your name, date of birth and mobile number. My code was like this...
#include<stdio.h>
int main(){
char name[50];
int Dob[50];
int mob[50];
scanf("%s %d %d", &name, &Dob, &mob);
printf("name : %s", name);
printf("dob : %d", Dob);
printf("Mob : %d", mob);
return(0);
}
However The output was something like this:
name : markdob : -515568656Mob : -515568856
Can someone please try to find my mistake?
CodePudding user response:
When you declare something like this int mob[50]
for a mobile number, what you are saying is you want to store 50 mobile numbers (the []
means an array of values where the number between those brackets is how many of those values you want), not one. For a single numeric value, you just need int mob
.
The same applies to how you've declared dob
- you are allocating space for 50 DOB's rather than one. Assuming that you are entering a numeric value like YYYYMMDD for it, you just need int dob
.
CodePudding user response:
To make your output format correct just add /n and you don't need to pass the size of variable for integer data type
#include<stdio.h>
int main(){
// Here your code !
char name[50];
int Dob;
int mob;
scanf("%s %d %d", &name, &Dob, &mob);
printf("name : %s", name);
printf("\n\ndob : %d", Dob);
printf("\n\nMob : %d", mob);
return 0;
}
CodePudding user response:
scanf("%s %d %d", &name, &Dob, &mob); You don't need & in scanf with array names, because array name is already a pointer to an address of it's 1st element
2) int Dob[50]; int mob[50];
if you want to print those int arrays, you have to use for loop. as an alternative its better to change those arrays to char too. In that case printf will print out everything till it find NULL CHARACTER which is \0.
All that combined will give you this code:
#include<stdio.h>
int main(){
// Here your code !
char name[50];
char Dob[50];
char mob[50];
scanf("%s %s %s", name, Dob, mob);
printf("name : %s", name);
printf("dob : %s", Dob);
printf("Mob : %s", mob);
return(0);
}
also you may want to make it a bit nicer:
#include<stdio.h>
int main(){
// Here your code !
char name[50];
char dob[50];
char mob[50];
printf("Enter your name : ");
scanf("%s", name);
printf("\n Enter your dob : ");
scanf("%s", dob);
printf("\n Enter your mobile number : ");
scanf("%s", mob);
printf("name : %s \n", name);
printf("dob : %s \n", dob);
printf("Mob : %s \n", mob);
return(0);
}