I am writing a simple program in C using structs. The user needs to enter some values for the struct - a name and age. After I enter the data for the first time, the second time the program just skips one of the fields and only wants me to enter the second field of the data. I can't figure out what's wrong.
struct Person {
char name[20];
int age;
};
void main(){
struct Person pArray[10];
for (int i = 0; i < 10; i++) {
printf("Please enter a name and age:\n");
printf("Name: ");
fgets(pArray[i].name, 20, stdin);
printf("Age: ");
scanf("%d", &pArray[i].age);
}
}
As you can see, after entering Jonathan and 45 for the first time, the second time it skipped the name and wants only the age. Why is this happening?
I try not to mix formatted and unformatted input (e.g., fgets and scanf). Here is your program using only fgets for input:
#include <stdio.h>
struct Person {
char name[20];
int age;
};
int main(){
struct Person pArray[10];
char numberBuffer[20];
for (int i = 0; i < 10; i++) {
printf("Please enter a name and age:\n");
printf("Name: ");
fgets(pArray[i].name, 20, stdin);
printf("Age: ");
fgets(numberBuffer, 20, stdin);
sscanf(numberBuffer, "%d", &pArray[i].age);
}
}
Related
I am trying to build a program which takes user input of employee details and prints it. I have separate functions for both of them.
Structure is as follows:
struct employee
{
int empId;
char name[20];
char empType[10];
int dd, mm, yyyy;
};
struct employee input()
{
struct employee e;
printf("Enter Employee ID: \n");
scanf("%d", &e.empId);
printf("Enter Employee name: \n");
scanf("%s", &e.name);
printf("Enter employee type: \n");
scanf("%s", &e.empType);
printf("Enter joining date: \n");
scanf("%d/%d/%d", &e.dd, &e.mm, &e.yyyy);
}
void display(struct employee emp[], int n)
{
printf("Employee ID \t Name \t Employee Type \t Joining date\n");
int i;
for (i = 0; i < n; i++)
{
printf("%d %s %s %d/%d/%d", emp[i].empId, emp[i].name, emp[i].empType, emp[i].dd, emp[i].mm, emp[i].yyyy);
}
}
int main()
{
int n = 5;
struct employee emp[n];
int i;
for(i = 0; i < n ;i++)
{
emp[i] = input();
}
display(emp, n);
return 0;
}
I am able to take the input properly but while printing I am getting all values as 0.
Requesting help!
Thanks!
You forgot about the return statement in the function input
//...
return e;
Also the arguments of these calls of scanf
printf("Enter Employee name: \n");
scanf("%s", &e.name);
printf("Enter employee type: \n");
scanf("%s", &e.empType);
are incorrect. You need to write
printf("Enter Employee name: \n");
scanf("%19s", e.name);
printf("Enter employee type: \n");
scanf("%9s", e.empType);
In general you should check that inputs were successful.
That for loop is unneccessary - you would end up printing the output 5 times, for some reason.
Also use typedef struct, it's convenient.
And don't type & when dealing with struct's string elements.
This code is a mess, by the way.
I want the user to enter "M" for Male or "F" for Female and the single character must be replaced by Male or Female but here the strcmp function is not working everytime time it is showing "Please enter correct value for Gender!!".
#include<stdio.h>
#include<string.h>
struct student{
char name[50];
int Roll_No;
char Gender[10];
};
int main()
{
int size;
printf("Enter the size for number of students you want to store:");
scanf("%d",&size);
struct student s[size];
int i;
for(i=0;i<size;i++)
{
printf("Enter the name of student s[%d]:",i);
fflush(stdin);
fgets(s[i].name,50,stdin);
printf("Enter the Roll Number of student s[%d]:",i);
scanf("%d",&s[i].Roll_No);
gen:printf("Enter your Gender(M-Male F-Female) for student s[%d]:",i);
fflush(stdin);
fgets(s[i].Gender,10,stdin);
if(strcmp(s[i].Gender,"M")==0)
{
strcpy(s[i].Gender,"Male");
}
if(strcmp(s[i].Gender,"F")==0)
{
strcpy(s[i].Gender,"Female");
}
else
{
printf("Please enter correct value for Gender!!\n");
goto gen;
}
}
printf("\nInformation entered of Students:\n");
for(i=0;i<size;i++)
{
printf("Name of student s[%d]:%s",i,s[i].name);
printf("Roll Number of student s[%d]:%d\n",i,s[i].Roll_No);
printf("Gender of student s[%d]:%s\n",i,s[i].Gender);
}
return 0;
}
The function fgets can append the entered string with the new line character '\n' that you should remove.
For example
fgets(s[i].Gender,10,stdin);
s[i].Gender[ strcspn( s[i].Gender, "\n" ) ] = '\0';
if(strcmp(s[i].Gender,"M")==0)
{
strcpy(s[i].Gender,"Male");
}
if(strcmp(s[i].Gender,"F")==0)
{
strcpy(s[i].Gender,"Female");
}
else
{
printf("Please enter correct value for Gender!!\n");
goto gen;
}
Pay attention to that instead of the using the goto statement you could enclose the code in the do-while statement.
Also to enter a letter there is no great sense to use the function fgets moreover when the entered string will be overwritten.
You could use an object of the type char and use a call of scanf like this
char gender;
scanf( " %c", &gender );
And then
if ( toupper( ( unsigned char )gender ) == 'M' )
{
strcpy(s[i].Gender,"Male");
}
//...
I have fixed your code. There was a number of errors.
You flush stdin
You mix scanf() and fgets()
Missing else when checking for "F"
There are other areas where to code could be enhanced. I let it as an exercise for you :-)
#include<stdio.h>
#include<string.h>
struct student {
char name[50];
int Roll_No;
char Gender[10];
};
int main()
{
int size;
struct student s[100];
int i;
char buf[100];
printf("Enter the size for number of students you want to store:");
fgets(buf, 100, stdin);
sscanf(buf, "%d", &size);
for (i = 0; i < size; i++)
{
printf("Enter the name of student s[%d]:", i);
fgets(s[i].name, 50, stdin);
printf("Enter the Roll Number of student s[%d]:", i);
fgets(buf, 10, stdin);
sscanf(buf, "%d", &s[i].Roll_No);
gen:printf("Enter your Gender(M-Male F-Female) for student s[%d]:", i);
fgets(buf, 10, stdin);
sscanf(buf, "%s", s[i].Gender);
if (strcmp(s[i].Gender, "M") == 0)
{
strcpy(s[i].Gender, "Male");
}
else if (strcmp(s[i].Gender, "F") == 0)
{
strcpy(s[i].Gender, "Female");
}
else
{
printf("Please enter correct value for Gender!!\n");
goto gen;
}
}
printf("\nInformation entered of Students:\n");
for (i = 0; i < size; i++)
{
printf("Name of student s[%d]:%s", i, s[i].name);
printf("Roll Number of student s[%d]:%d\n", i, s[i].Roll_No);
printf("Gender of student s[%d]:%s\n", i, s[i].Gender);
}
return 0;
}
I have this project where I have to create a struct array with C language for students' data, and I can't seem to get past this warning by my variable arr_student. The warning says that I have not initialized the variable, and whenever I try to debug it the IDE says that it has a memory error involving where it goes. I want to be able to declare it and use it as a way to get to the variables created in my struct array. If anyone knows what I could be missing, that would be greatly appreciated!
#include <stdio.h>
#include <string.h>
#define numero 2 //This number is the limiter for the number of students
struct Student
{ //Define struct array with student information
char id[50];
char gpa[50];
char address[50];
char phone_number[50];
char first_name[50];
char last_name[50];
};
int main(struct Student arr_student[numero])
{
int i; //Counter
char tempvalue[50]; //Temporary variable to store data in the array
char search[50]; //Search value input by user
int result = 1; //Initialized result to false
for (i = 0; i < numero; i++)
{
//Asks user for input on student information.
printf("\nEnter the information for student %d\n\n", i + 1);
printf("\nEnter first name: ");
scanf("%s", tempvalue);
printf("%s", tempvalue);
//prints value to verify if tempvalue recieved
strcpy(arr_student[i].first_name, tempvalue);
//error begins with the arr_student being underlined
printf("\nEnter last name: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].last_name, tempvalue);
printf("\nEnter student id: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].id, tempvalue);
printf("\nEnter student gpa: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].gpa, tempvalue);
printf("\nEnter student address: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].address, tempvalue);
printf("\nEnter student phone number: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].phone_number, tempvalue);
}
printf("Enter the last name of the student you wish to examine data for: ");
//Asks input from the user for a name to search the data for
scanf("%s", search);
for (i = 0; i < numero; i++)
{
result = strcmp(search, arr_student[i].last_name);
}
if (result == 0) //A match is found in the array
{
printf("Here is the data on the student: %s", search);
printf("First Name\t Last Name\t ID\t GPA\t Address\t Phone Number\n");
//Prints out student information
printf("%s\t%s\t%s\t%s\t%s\t%s\n",
arr_student[i].first_name, arr_student[i].last_name, arr_student[i].id,
arr_student[i].gpa, arr_student[i].address, arr_student[i].phone_number);
}
else
{
printf("The name you have entered is not in our system, please try again");
return;
}
return 0;
}
Change the invalid main() definition from
int main(struct Student arr_student[numero])
{
to
int main(void) {
struct Student arr_student[numero] = {0};
Use width limited input.
char tempvalue[50];
// scanf("%s", tempvalue);
scanf("%49s", tempvalue);
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 4 years ago.
I wrote this C program to enter names and ages of 3 people. But the output wasn't my expectation. It was able to enter name and age for the first person, but it wasn't able for second and third persons. Please help.
#include <stdio.h>
#include <string.h>
int main()
{
int i, age;
char name[20];
for(i=0; i<3; i++)
{
printf("\nEnter name: ");
gets(name);
printf("Enter age: ");
scanf(" %d", &age);
puts(name);
printf(" %d", age);
}
return 0;
}
In short: Your 2nd puts is processing the '\n' from your scanf.
Fix by adding getchar(); after scanf
Explanation:
1st iteration:
printf("\nEnter name: ");
gets(name); // line is read from input
printf("Enter age: ");
scanf(" %d", &age); // a number is read from input, and the newline char ('\n') remains in buffer
puts(name);
printf(" %d", age);
2nd iteration:
printf("\nEnter name: ");
gets(name); // previously buffered newline char is read, thus "skipping" user input
printf("Enter age: ");
scanf(" %d", &age);
puts(name);
printf(" %d", age);
Same goes for 3rd iteration, and this is why you lose user input
The best way to store information of more than one person is to use struct, like
struct person {
int age;
char name[20];
};
and make array of struct, like
struct person people[3];
than use loop with accessing people[i].age and people[i].name, e.g.:
#include <stdio.h>
#include <string.h>
struct person {
int age;
char name[20];
};
#define ARR_SIZE 3
int main(int argc, char* argv[])
{
struct person people[ARR_SIZE];
int i;
char *lastpos;
for(i = 0; i < ARR_SIZE; i++)
{
printf("\nEnter name: ");
scanf(" %s", people[i].name);
if ((lastpos=strchr(people[i].name, '\n')) != NULL) *lastpos = '\0'; // remove newline from the end
printf("Enter age: ");
scanf(" %d", &people[i].age);
}
printf("This is the people you entered:\n");
for(i = 0; i < ARR_SIZE; i++)
{
printf("%d : %s : %d\n", i+1, people[i].name, people[i].age);
}
return 0;
}
UPDATE:
As you see I use scanf(" %s", people[i].name); instead of gets(people[i].name); to read name from stdin. Try both option for the following cases:
enter short name (e.g. John) and correct age (e.g. 15)
enter two word name (e.g. John Smith) and correct age (e.g. 17)
enter short name and uncorrect age (e.g. five)
Then read articles about value returned by scanf and cleaning input buffer
This is a program for a class project. It is suppose to be able to create and edit structures. The CreatRec function works fine. For the ModifyRec I am trying to send it the array by pointers in order to avoid having to "copy" the data. However, I am having trouble getting it to actually change the array. ATM The line at the bottom (gr[change].lastname= *info;) is not working at all. I really have no clue what I am doing wrong here.
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
struct student{
int recordname;
char lastname[10];
char firstname[10];
float math;
float english;
float science;
};
//prototypes
int menu();
struct student CreatRec(int);
void ModifyRec(struct student*);
void main()
{
int option, j;//option will be for users menu choice, j makes for loop work for creatrec
struct student grades[10];
j = 0;
option=Menu();
if (option == 1)
for (j = 0; j<10; j++)
(grades[j + 0]) = CreatRec(j);
else if (option==2)
ModifyRec(grades);//dont need & is smart bc array
printf("%s",grades[0].lastname);//This line is checking to see if ModifyRec actaully worked
//free(grades);2
while (1);
}
int Menu()
{
int choi;
printf("Please choose one of the following options.\n 1) Create New Student Records.\n 2) Modify an Existing Student Record\n");
printf(" 3) Print a New Sutdent Record.\n 4) Quit\n");
scanf("%d", &choi);
return choi;
}
struct student CreatRec(int i)
{
struct student qr;
//qr = (struct student*)malloc(sizeof(struct student)*6);
printf("RecordNum %i\n", i);
printf("Please enter last name-->");
scanf("%s", &qr.lastname);
printf("Please enter first name-->");
scanf("%s", &qr.firstname);
printf("Please math grade-->");
scanf("%f", &qr.math);
printf("Please english grade-->");
scanf("%f", &qr.english);
printf("Please science grade-->");
scanf("%f", &qr.science);
return qr;
}
void ModifyRec(struct student gr[])
{
int change;
char feild[10], info[10];
printf("Which record would you like to change?\n");
scanf("%d", &change);
rewind(stdin);
printf("Which feild would you like to edit?\n");
scanf("%s", &feild);
rewind(stdin);
printf("Enter info\n");
scanf("%s", &info);
if (!strcmp("lastname", feild))
gr[change].lastname= *info;//NOT WORKING
}
First of all I do not see a great sense in expression grades[j + 0] of statement
for (j = 0; j<10; j++)
(grades[j + 0]) = CreatRec(j);
These statements
printf("Please enter last name-->");
scanf("%s", &qr.lastname);
printf("Please enter first name-->");
scanf("%s", &qr.firstname);
have to be substituted for
printf("Please enter last name-->");
scanf("%s", qr.lastname);
printf("Please enter first name-->");
scanf("%s", qr.firstname);
And this statement
if (!strcmp("lastname", feild))
gr[change].lastname= *info;//
has to be substituted for
if (!strcmp("lastname", feild))
strcpy( gr[change].lastname, info );
gr[change].lastname is a char array, not a pointer. You can't reassign it. In this case, you probably ought to do scanf("%s", gr[change].lastname); and skip char info[10] altogether.