Sunday, August 2, 2009

Anyone know about C programming?

I've decided to drop the class but I'm still trying to learn.





I'm trying to do some exercises from the book. One asks





"Define a structure student_record which has following members: first name, last name, idNum. Write a program to allow user to input all information of 3 students. Save them in an array and print them out accordingly"





I just did a test code to see if I could save just one....





#include %26lt;stdio.h%26gt;


int main()


{


struct student_record


{


int firstn;


int lastn;


int id;


};





struct student_record student1, student2, student3;








printf("Entry 1\n");


printf("First name\n");


scanf("%i", %26amp;student1.firstn);


printf("Last name?\n");


scanf("%i", %26amp;student1.lastn);


printf("ID?\n");


scanf("%i", %26amp;student1.id);





return 0;


}





When I compile and execute the code though it asks, for the first name, when I enter that it goes straight thru "last name and ID" without even asking for input...Also how would you put that in an array? I trued doing a students[3] structure but it didn't work.

Anyone know about C programming?
First of all, move the struct definition outside of the main function so it will be available to other functions you make. I'm surprised the compiler even accepts it the way it is now.





Next, you're trying to store the names (which should be strings) in integers. declare them as character arrays (or pointers and dynamically allocate them later, but fixed-length arrays are easier) and use "%s" in scanf to read the strings.





To use an array, declare it like:





struct student_record students[3];





and reference the individual elements like:





%26amp;students[i].id


No comments:

Post a Comment