Could I please have an explanation of what I am doing wrong.The program is for inputting and displaying student details. It must use a structure and have 2 functions; one to capture(which is to be passed by reference) and another to display (which is to be passed by value.
Here is my code:
#include <stdio.h>
struct Students{
int ID;
char name[50];
int age;
char address[100];
char course[30];
} aStudent[5];
void capture(char *name , int *age , char *address, char *course){
int i;
for(i=0; i<5; i++){
aStudent[i].ID = i+1;
printf("\nFor Student number %d:\n",aStudent[i].ID);
printf("Enter Student Name: ");
scanf ("%s", &aStudent[i].name);
printf("Enter Student Age: ");
scanf ("%d", &aStudent[i].age);
printf("Enter Student Address: ");
scanf ("%s", &aStudent[i].address);
printf("Enter Course: ");
scanf ("%s", &aStudent[i].course);
}
}
void display(char name, int age , char address, char course){
int i;
for(i=0; i<5; i++){
printf("\nStudent %d:\n",aStudent[i].ID);
printf("Name: %s\t\tAge: %d\t\tAddress: %s\t\tCourse:
%s",aStudent[i].name, aStudent[i].age, aStudent[i].address,
aStudent[i].course);
printf("\n");
}
}
void main()
{
int option, age;
char name, address, course;
printf("\t...Welcome to the Student Data System...\n\n");
printf("\nPlease Select An Option: \n1. Input Student Data\n2. View
Student Data\n3. Exit Syatem\n\n");
scanf("%d",&option);
switch(option){
case 1:
printf("Enter Student Details:\n");
capture(name, age , address, course);
break;
case 2:
printf("\nDisplaying Information:\n");
display(name, age , address, course);
break;
case 3:
close();
break;
default:
printf("\nSorry, your option is not valid.");
}
}
I have tested a number of times and it's working, but I'm getting these error messages:
Errors are shown for every argumety I've used
Also, is there a way or a line(s) of code i can use to return to the start of the switch when I am done with one of the cases - A "Return to Main Menu"?
First of all, variables you have tried to pass (either by value or by reference) when you are calling the two functions capture() and display(), haven't used anywhere because you are dealing directly with the members of the structure Students when you are capturing or displaying the results.
And the reasons you are getting syntax errors are because the capture() is expecting the addresses of the variables (&name,&age,&address,&course) and you are passing variables (name,age,address,course) themselves. And also you are using,
scanf ("%s", &aStudent[i].name);
instead of
scanf ("%s", aStudent[i].name);
In my opinion instead of making the Structure array global, declaring it inside main function and passing the whole structure array to the capture() as a reference and passing it by value to the display() is better to your objective as you need to use both call by value and reference in your code.
I have edited your code a bit and added the return to main menu option. It works for me and I apologize if my answer is long and hard to understand because this is my first answer in stackoverflow. Thanks!
#include <stdio.h>
struct Students
{
int ID;
char name[50];
int age;
char address[100];
char course[30];
};
void capture(struct Students *aStudent)
{
int i;
for(i=0; i<2; i++)
{
aStudent[i].ID = i+1;
printf("\nFor Student number %d:\n",aStudent[i].ID);
printf("Enter Student Name: ");
scanf ("%s", aStudent[i].name);
printf("Enter Student Age: ");
scanf ("%d", &aStudent[i].age);
printf("Enter Student Address: ");
scanf ("%s", aStudent[i].address);
printf("Enter Course: ");
scanf ("%s", aStudent[i].course);
}
}
void display(struct Students aStudent[])
{
int i;
for(i=0; i<2; i++)
{
printf("\nStudent %d:\n",aStudent[i].ID);
printf("Name: %s\t\tAge: %d\t\tAddress: %s\t\tCourse: %s",aStudent[i].name, aStudent[i].age, aStudent[i].address,aStudent[i].course);
printf("\n");
}
}
void main()
{
struct Students aStudent[2];
int option;
char choice = 'Y';
printf("\t...Welcome to the Student Data System...\n\n");
while(choice == 'Y' || choice == 'y')
{
printf("\nPlease Select An Option: \n1. Input Student Data\n2. View Student Data\n3. Exit Syatem\n\n");
scanf("%d",&option);
switch(option)
{
case 1:
printf("Enter Student Details:\n");
capture(aStudent);
printf("Return to main menu? (Y/N) :");
scanf(" %c",&choice);
break;
case 2:
printf("\nDisplaying Information:\n");
display(aStudent);
printf("Return to main menu? (Y/N) :");
scanf(" %c",&choice);
break;
case 3:
close();
break;
default:
printf("\nSorry, your option is not valid.");
}
}
}
You have not initialized your string instead you have initialized a character! char name, address, course; If you have used 'char *name, *address, *course;' or char name[100], address[100], course[100]; you might have got the answer ! If you use the above case you should scan using scanf("%s",name); ! Hope I answered your question !
Related
Here is my code. I want it to ask me questions in a sequence. But whenever I enter my choice and put my name it didn't allow me to ask further. How to deal with that?
#include <stdio.h>
#include <stdlib.h>
int new_acc();
int main(){
int one=1, two=2, three=3, four=4, five=5, six=6, seven=7, new_account;
printf("-----WELCOME TO THE MAIN MENU-----\n\n");
printf("%d. Create new account\n",one);
printf("Enter you choice: ");
if (scanf("%d",&one)){
new_account = new_acc(); // calling a function
}
return 0;
}
int new_acc(){
int id; char name;
printf("Enter your name: ");
scanf("%c\n",&name);
printf("Enter your ID card number: ");
scanf("%d\n",&id);
return 0;
}
If you typed Enter after typing nubmer for the MAIN MENU, the newline character remains in the buffer.
Then, is is read as the name via %c.
After that, if you typed, for example, alphabet as name, it will prevent it from reading the number id.
To avoid this, you can put a space before %c to have it skip the newline character.
Also you won't be have to skip after reading name and id, so you should remove \n in scanf() after %c and %d for them.
int new_acc(){
int id; char name;
printf("Enter your name: ");
scanf(" %c",&name); /* add space and remove \n */
printf("Enter your ID card number: ");
scanf("%d",&id); /* remove \n */
return 0;
}
By the way, the above code will allow only one alphabet as name.
To support multi-character name (without space character), you should use an array of char and %s with length specified.
int new_acc(){
int id; char name[1024];
printf("Enter your name: ");
scanf(" %1023s",name); /* don't use & here, and size limit is buffer size - 1 (-1 for terminating null character) */
printf("Enter your ID card number: ");
scanf("%d",&id);
return 0;
}
If you want to support name with space characters, you can use %[\n] (read until newline character) instead of %s.
int new_acc(){
int id; char name[1024];
printf("Enter your name: ");
scanf(" %1023[^\n]",name);
printf("Enter your ID card number: ");
scanf("%d",&id);
return 0;
}
Seems like you want to use an object oriented programming paradigm in this. To so do, you should define an "object" with struct and save the new account with that:
#define MAX 50
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Account {
int id;
char name[MAX];
};
struct Account new_acc();
int main(){
int choice;
struct Account new_account;
printf("-----WELCOME TO THE MAIN MENU-----\n\n");
printf("1. Create new account\n");
printf("Enter you choice: ");
scanf("%d",&choice);
switch(choice) {
case 1:
new_account = new_acc();
break;
default:
printf("Not a valid option\n");
return 1;
}
return 0;
}
struct Account new_acc(){
char name[MAX];
int id;
struct Account new;
printf("Enter your name: ");
scanf("%c\n",name);
printf("Enter your ID card number: ");
scanf("%d\n",&id);
strcpy(new.name, name);
new.id = id;
return new;
}
Pay attention because this code is very vulnerable to buffer overflows. Plus, I edited your check for the option in main because scanf returns 1 if reads whatever value successfully.
Use This Code i have modfified a little bit
int new_acc(){
int id; char name[10];
printf("Enter your name: ");
scanf("%s",name);
printf("Enter your ID card number: ");
scanf("%d",&id);
return 0;
}
I am taking a very basic C course, and I have run into a problem. My code is supposed to take someone's info, create a profile, and then print the information at the end. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
typedef struct record
{
char lastname[30];
char firstname[30];
int id;
char gender;
int monthOfBirth;
int dayOfBirth;
int yearOfBirth;
} HealthProfile;
void setID(HealthProfile *HPP){
int id;
printf("please enter your ID: ");
scanf("%d", &id);
HPP->id=id;
}
void setGender(HealthProfile *HPP){
char gender;
printf("please enter yomeur M or F for your gender: ");
scanf("%c",&gender);
HPP->gender=gender;
}
void setFirstName(HealthProfile *HPP){
char firstname[30];
printf("please enter your first name: ");
scanf("%s",&firstname);
HPP->firstname=firstname;
}
void setLastName(HealthProfile *HPP){
char lastname[30];
printf("please enter your last name: ");
scanf("%s",&lastname);
HPP->lastname=lastname;
}
void setDoB(HealthProfile *HPP){
int dayOfBirth;
printf("please enter your DoB: ");
scanf("%d", &dayOfBirth);
HPP->dayOfBirth=dayOfBirth;
}
void setMoB(HealthProfile *HPP){
int monthOfBirth;
printf("please enter your MoB: ");
scanf("%d", &monthOfBirth);
HPP->monthOfBirth=monthOfBirth;
}
void setYoB(HealthProfile *HPP){
int yearOfBirth;
printf("please enter your YoB: ");
scanf("%d", &yearOfBirth);
HPP->yearOfBirth=yearOfBirth;
}
int main()
{
HealthProfile *HPP;
HPP=(HealthProfile*) malloc(sizeof(HealthProfile));
setID(HPP);
setGender(HPP);
setLastName(HPP);
setFirstName(HPP);
setDoB(HPP);
setMoB(HPP);
setYoB(HPP);
printf("\n Profile information.....");
printf("ID number: %d\n", HPP->id);
printf("Gender: %c\n", HPP->gender);
printf("Name: %s/n",HPP->firstname);
printf(" %s", HPP->lastname);
printf("Month of birth: %d\n", HPP->monthOfBirth);
printf("Day od birth: %d\n", HPP->dayOfBirth);
printf("Year of birth: %d\n", HPP->yearOfBirth);
}
The part that is giving me the error is these two lines:
**HPP->lastname=lastname;**
and
**HPP->firstname=firstname;**
Whenever I try to run it the equal sign is highlighted red and my code gives me the "assignment to expression with array type" error. Even after looking it up and trying things for almost two hours I couldn't figure it out, so can someone help me, please?
The fields HPP->lastname and HPP->firstname are both arrays, and as the error message states you cannot assign directly to an array.
The way you copy one string to another is to use the strcpy function:
strcpy(HPP->firstname, firstname);
Of course, you can get rid of the copy altogether and read directly into the target array instead of a temporary.
scanf("%s", HPP->firstname);
I'm brand new to C and I'm trying to figure out what in the world is causing this. Another similar question said that I had to download another library but that hasn't fixed the issue. So, hopefully someone can spot my problem.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum Subject {SER=0, EGR=1, CSE=2, EEE=3} subject;
struct Course {
enum Subject subject;
int number;
char teacher[1024];
int hours;
} *course;
//place to store course information
struct Course* CourseCollection = NULL;
//number of courses in the collection. also the index of the next empty element.
int courseCount = 0;
void branching(char option);
void course_insert(struct Course course);
int main() {
char input_buffer;
printf("Welcome to ASU Class Schedule\n");
//menu and input loop
do {
printf("\nMenu Options\n");
printf("------------------------------------------------------\n");
printf("a: Add a class\n");
printf("d: Drop a class\n");
printf("s: Show your classes\n");
printf("q: Quit\n");
printf("\nTotal Credits: %d\n\n", courseCount);
printf("Please enter a choice ---> ");
scanf(" %c", &input_buffer);
branching(input_buffer);
} while (input_buffer != 'q');
return 0;
}
//takes a character representing an inputs menu choice and calls the appropriate
//function to fulfill that choice. display an error message if the character is
//not recognized.
void branching(char option) {
int prefix, courseNum, credits;
char instructor;
struct Course course1;
switch(option) {
case 'a' :
printf("Adding a class");
printf("\nWhat is the subject (SER=0, EGR=1, CSE=2, EEE=3)? ");
scanf(" %d", &prefix);
course1.subject = prefix;
printf("\nWhat is the course number (e.g. 334)? ");
scanf(" %d", &courseNum);
course1.number = courseNum;
printf("\nHow many credits is the class? ");
scanf(" %d", &credits);
course1.hours = credits;
printf("\nWhat is the name of the teacher? ");
scanf(" %s", &instructor);
strlcpy(course1.teacher, instructor, 1024);
printf(" %s %d", course1.subject, course1.number);
courseCount++;
course_insert(course1);
break;
case 'd' :
// TODO
break;
case 's' :
// TODO
break;
case 'q' :
printf("Goodbye ");
break;
default :
printf("Error: Invalid Input. Please Try Again. ");
break;
}
void course_insert(struct Course course) {
CourseCollection = malloc(sizeof(course)*courseCount);
}
}
The problem is a syntactical bug; the function definition for course_insert() is inside the curly braces of the function definition of branching(). You need to fix the curly braces:
void branching (char option)
{
// Code for function
}
void course_insert(struct Course course)
{
CourseCollection = malloc(sizeof(course)*courseCount);
}
I was practicing array of structure. I made the following program and there were no compiling errors.But when i try to run it(I guess these errors are called runtime errors?),it stops working just after accepting the roll number. I wonder what wrong i did.
I use Dev c++ and gcc compiler.
Here's the code:
#include<stdio.h>
struct student{
char Fname[];
char Lname[];
int reg_no;
int Class;
char sec;
};
void enterinfo(student *,int);
void Display(student *,int);
int main()
{
int i;
printf("\t\t\t Enter student's information\n\n\n\n");
printf("How many students are there in you're school: ");
scanf("%d",&i);
student ob[i],*ptr;
ptr=ob;
enterinfo(ptr,i);
Display(ptr,i);
}
void enterinfo(student *e,int y)
{
char CONT='y';
for (int j=0;j<y && (CONT=='y' || CONT=='Y');j++)
{
printf("Enter Students First Name: ");
scanf("%s",e->Fname);
printf("Enter Students Last Name: ");
scanf("%s",e->Lname);
printf("Enter Roll number: ");
scanf("%d",e->reg_no);
printf("Enter class: ");
scanf("%d",e->Class);
printf("Enter Section: ");
scanf("%d",e->sec);
printf("\n\n\n\n Do you want to enter more? : ");
scanf("%c",&CONT);
}
}
void Display(student *e,int y)
{
char CONT='y';
for (int j=0;j<y;j++)
{
printf("Students name : %s %s",e->Fname,e->Lname);
printf("Enter Roll number: %d",e->reg_no);
printf("class: %d",e->Class);
printf("Enter Section: %d",e->sec);
}
}
I've made the following changes to your code and it started working for me:
char Fname[]; --> char Fname[100];
char Lname[]; --> char Lname[100];
char sec; --> int sec; This is needed for scanf.
scanf("%d",e->reg_no); --> scanf("%d",&e->reg_no);
scanf("%d",e->Class); --> scanf("%d",&e->Class);
scanf("%d",e->sec); --> scanf("%d",&e->sec);
adding \n to the end of printf strings in Display
Please note that scanf("%s", ...) is insecure and it can cause a crash the input string is longer than the array size you're reading it to, i.e. if the user types a name of at least 100 bytes.
Please note that you should always check the return value of scanf, and abort early on error (i.e. if it doesn't return 1 in your case).
Please note that in C++ the istream methods (http://en.cppreference.com/w/cpp/header/istream) provide a safer way to read the input.
Here:
scanf("%d",e->reg_no);
you should insert a '&' symbol before e->reg_no. But I can see many other problems once you solve this...
You can use below code, it will run on both linux & windows. Your program halts because of:
scanf("%d",&e->reg_no);
printf("Enter class: ");
scanf("%d",&e->Class);
printf("Enter Section: ");
scanf("%d",&e->sec);
you did not use & which is must for int, char, float data types as it is used as reference of the variable.
#include
struct student{
char Fname[30];
char Lname[30];
int reg_no;
int Class;
char sec[5];
};
void enterinfo(student *,int);
void Display(student *,int);
int main()
{
int i;
printf("\t\t\t Enter student's information\n\n\n\n");
printf("How many students are there in you're school: ");
scanf("%d",&i);
student * ob = new student[i];
enterinfo(ob,i);
Display(ob,i);
}
void enterinfo(student *e,int y)
{
char CONT='y';
for (int j=0;jFname);
printf("Enter Students Last Name: ");
scanf("%s",e->Lname);
printf("Enter Roll number: ");
scanf("%d",&e->reg_no);
printf("Enter class: ");
scanf("%d",&e->Class);
printf("Enter Section: ");
scanf("%s",e->sec);
getchar();//to eat newline/ enter char of previous statement
printf("\n\n\n\n Do you want to enter more? : ");
scanf("%c",&CONT);
}
}
void Display(student *e,int y)
{
for (int j=0;jFname,e->Lname);
printf("\nEnter Roll number: %d",e->reg_no);
printf("\nclass: %d",e->Class);
printf("\nEnter Section: %s\n",e->sec);
}
}
This question already has answers here:
using scanf function with pointers to character
(6 answers)
Closed 3 years ago.
noob question here:
I'm trying to write a simple menu interface, but I keep getting a segmentation fault error and I can't figure out why.
#include <stdlib.h>
#include <stdio.h>
int flush(); int add(char *name, char *password, char *type); int delete(char *name);
int edit(char *name, char *password, char *type, char *newName, char *newPassword, char *newType);
int verify(char *name, char *password);
int menu(){
int input;
char *name, *password, *type, *newName, *newPassword, *newType;
printf("MAIN MENU \n ============\n");
printf("1. ADD\n");
printf("2. DELETE\n");
printf("3. EDIT\n");
printf("4. VERIFY\n");
printf("5. Exit\n");
printf("Selection:");
scanf("%d", &input);
flush();
switch (input){
case 1:
printf("%s\n", "Enter Name:");
scanf("%s", name);
flush();
printf("%s\n", "enter password" );
scanf("%s", password);
flush();
printf("%s\n","enter type" );
scanf("%s",type);
add(name, password, type);
menu();
break;
case 2:
printf("Enter Name:" );
scanf("%s",name);
flush();
delete(name);
menu();
break;
case 3:
printf("Enter Name:\n");
scanf("%s",name);
flush();
printf("Enter Password\n");
scanf("%s", password);
flush();
printf("enter type:\n");
scanf("%s", type);
flush();
printf("enter your new username:\n");
scanf("%s",newName);
flush();
printf("enter your new password\n");
scanf("%s", newPassword);
flush();
printf("enter your new type\n");
scanf("%s",newType);
flush();
edit(name, password, type, newName, newPassword, newType);
menu();
break;
case 4:
printf("Enter Name\n");
scanf("%s",name);
flush();
printf("Enter Password\n");
scanf("%s",password);
flush();
verify(name, password);
menu();
break;
case 5:
return 0;
default:
printf("invalid input, please select from the following:\n");
menu();
}
return 0;
}
int flush(){
int ch;
while ((ch = getchar()) != EOF && ch != '\n') ;
return 0;
}
I get the segmentation fault after entering two fields, in any menu option
You need to initialize your pointers. Alternatively, use stack-allocated arrays.
For example, instead of char *name, do char name[20]. (Note that this will limit your input to 19 characters; use a larger buffer if necessary.)
Right now, you are passing uninitialized pointers into scanf() which effectively means that scanf() is going to write to an undefined area of memory. It might work on one execution and then fail on the next. It might corrupt memory elsewhere in the process' address space.
Don't use uninitialized variables, and consider turning up your compiler warnings as high as they will go; the compiler can catch errors like this and emit a warning.
Instead of using *name, *password,.. use name[100], password[100],... If you want name, password, .. to be pointer then allocate memory using malloc or calloc before calling scanf.