-
Character Array Entry
I wrote a program to accept an array of names and ages, then sort the list in ascending order, but I can't seem to get my gets function to work. I think the issue is in like 33, but I can't be sure. When I compile, it doesn't accept the string, and immediately prints the "Age: ".
Any help would be greatly appreciated!
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//definitions
char names[100][100], *name_ptr;
int ages[100];
int i, k, size, age;
printf(" Enter Name and Age \n");
printf("\n=============================\n");
//define array size by number of desired names
printf(" Number of names: ");
scanf("%d", &size);
//validate entry
if ( (size <= 0) || (size > 10) )
{
printf("Invalid Size\n");
printf("Number of names: ");
scanf("&d", &size);
}
printf("\n=============================\n");
for (i=0; i<size; i++)
{
//get names
printf("Name: ");
name_ptr = gets(names[i]);
printf("\n");
//get ages
printf("Age: ");
scanf("%d", &age);
//validate input
if ((age <= 0) || (age > 150))
{
printf("Invalid Input\n");
printf("Reinput Age: ");
scanf("&d", &age);
}
ages[i] = age; //assign age to the ages array
printf("\n\n");
}
printf("\n=============================\n");
//scan through ages array for every age possible (1-150)
//if the value of ages array is eaqual to the age,
//put that name and age
for (i=1; i<150; i++)
{
for (k=0; k<size; k++)
{
if (ages[k] = i)
{
puts(names[k]);
puts(ages[k]);
}
}
}
return 0;
}
-
1. Make sure your warnings are cranked up, and heed them.
Code:
main.c|22|warning: too many arguments for format|
main.c|41|warning: too many arguments for format|
main.c|55|warning: suggest parentheses around assignment used as truth value|
main.c|58|warning: passing argument 1 of 'puts' makes pointer from integer without a cast|
Code:
scanf("&d", &size);
// You mean "%d" not "&d"
scanf("&d", &age);
// You mean "%d" not "&d"
if (ages[k] = i)
// You mean '==' (equality operator) not '=' (assignment operator)
puts(ages[k]);
// "ages" is an integer array, not a character array
2. Don't write all your code in one go and wonder why you get many warnings/errors. Write some code, compile, test, verify. Write some more, etc.
When you fix these, you'll notice that some options get skipped. That's because when you "scanf()" then press enter, it leaves the newline in the input buffer, which gets eaten up by the following "gets()".
Which leads to why should not use "gets()": FAQ > Why gets() is bad / Buffer Overflows - Cprogramming.com
-
I know it's better to write and compile bits of code at a time, but usually I end up writing a bulk of my code in notepad at work and bring it home to debug. I've made the changes to my code, and I'll compile it later tonight. Thanks for the help!