I have just learnt about arrays. I was trying to create a database program using arrays. It’s a very basic program.
#include<stdio.h>
#define N 1 //number of entries needed
int main()
{
int i, k = 1, l = 1, w, x = 0, y = 0;
int rollnum[N], hsc[N], cet[N], a[N], b[N];
char name[100], city[100], c;
for(i = 0; i < N; i++)
{
printf("%d.\n", (i+1));
printf("Enter first name : ");
do
{
c = getchar();
if(c != '\n')
{
name[k] = c;
k++;
}
}
while(c != '\n');
a[i] = k;
k++;
printf("\n");
printf("Enter roll number : ");
scanf("%d", &rollnum[i]);
printf("\n");
getchar();
printf("Enter city : ");
do
{
c = getchar();
if(c != '\n')
{
city[l] = c;
l++;
}
}
while(c != '\n');
b[i] = l;
l++;
printf("\n");
printf("Enter HSC percentage : ");
scanf("%d", &hsc[i]);
printf("\n");
printf("Enter CET marks : ");
scanf("%d", &cet[i]);
printf("\n");
getchar();
}
printf("\n\n\n");
k = 1;
l = 1;
for(i = 0; i < N; i++)
{
printf("Entry %d\n", (i+1));
printf("Student Name : ");
x = (a[i] - x);
for(w = 0; w < x; w++ && k++)
putchar(name[k]);
putchar('\n');
printf("Roll number : %d", rollnum[i]);
printf("\n");
printf("City : ");
y = (b[i] - y);
for(w = 0; w < y; w++ && l++)
putchar(city[l]);
putchar('\n');
printf("Marks : \n");
printf("\t");
printf("HSC : %d ", hsc[i]);
printf("\t");
printf("CET : %d / 200", cet[i]);
printf("\n\n\n");
}
return 0;
}
The program is not functioning the way I want it to! When I enter a name, the first letter is being printed out twice, same is the case with city! If I put 2 entries by modifying my ‘N’ , I’m getting the first letters of name and address(of second entry) as garbage values . I don’t think there is any error in my logic, because i tried doing it manually in my notebook and I did not find any fault in it.
Can anyone help me find the mistake? I know the program might not at all be good and efficient, but I’m just trying out stuff that I’ve learnt!
You have made some mistakes initializing some variables. Also you don’t have to read a string one character at a time. You can use
scanf("%s", someString)to read a whole string.And here is a working code that looks a lot more cleaner:
It works for multiple entries too.
In order to make your program work you have to replace this:
with this:
the problem was that you didn’t calculate the length of the words correctly, and also another error that I still can’t explain but I removed that to.