C Program exits before taking input from user - c

Why does my program close before taking the input for k and then displaying it.
I am writing a code for a menu based program so I need to take input from user after he has entered the information so I can have 1.Print names 2.Exit
while doing this I realized my program didn't take the input and just skipped the part where it is supposed to take value of l from user. So trying to debug it I deleted stuff and came down to this simple program and realized it still wont work any idea why?
#include <stdio.h>
struct student
{
char name[50];
char lname[50];
float marks;
} s[15];
int main ()
{
int i, j,k;
printf("Please enter the number of students:\n");
scanf ("%d", &j);
printf ("Please enter the information for students as asked.\n");
for (i = 0; i < j; i++)
{
scanf ("%s %s %f\n", s[i].name, s[i].lname, &s[i].marks);
}
printf("Please enter a number\n");
scanf ("%d", &k);
printf("your number was %d", k);
return 0;
}

scanf ("%s %s %f\n", s[i].name, s[i].lname, &s[i].marks);
should be
scanf ("%s %s %f", s[i].name, s[i].lname, &s[i].marks);
The \n in scanf just consumes newline char. It will continue consuming newline until a non-newline char is found, which is put back into stdin for the next IO operation

Try this Code
#include<stdio.h>
typedef struct student
{
char name[50];
char lname[50];
int mark;
}S;
int main ()
{
int i, j,k;
printf("Please enter the number of students:\n");
scanf ("%d", &j);
S record[j];
for (i = 0; i < j; i++) {
printf ("Please enter the information for %d student as asked.\n",i+1);
scanf ("%s %s %f",record[i].name, record[i].lname, &record[i].mark);
}
printf("Please enter a number\n");
scanf ("%d", &k);
printf("your number was %d \n", k);
return 0;
}
You were declaring structure student array in the structure declaration itself.you have to declare the array in main function.

Related

How do I repeat entering data in a struct using C?

I'm new to C, and currently trying to practice on some simple codes, and I'm currently stuck with that next one.
After entering the first customer data, and repeat the code... View_customer function fails to show the saved data, and when I try to go to enter a second account data, it fails at the second entry.
#include<stdio.h>
#include<stdlib.h>
typedef struct cust{
char name[60];
int acc_no,age;
char address[60];
char citizenship[15];
double phone;
char acc_type[10];
} cust;
void new_account(int num);
void view_account(int num);
int main()
{
cust customers[10];
char answer;
int n;
int cutomer_number=1;
int cutomer_num2;
printf("Welcome To The program X: \n");
do{
printf("\n How can we serve you today? \n 1.Create a new account \n 2.Print an existing Account info \n ");
scanf("%d",&n);
if (n==1)
{
new_account(cutomer_number);
cutomer_number++;
}else {
printf("Please enter your Cust number: ");
scanf(" %d",&cutomer_num2);
view_account(cutomer_num2);
};
printf("\n Press Y to continue. Press any Key To Exit: ");
scanf(" %c",&answer);
}while (answer == 'Y' || answer == 'y');
return 0;
}
void view_account(int n)
{
cust customers[n];
printf("Your name is %s \n ", customers[n].name);
printf("Your age is %d \n", customers[n].age);
printf("Your address is %s \n", customers[n].address);
printf("Your citizenship is %s \n", customers[n].citizenship);
printf("Your phone number is %f \n", customers[n].phone);
printf("Your account type is %s \n", customers[n].acc_type);
};
void new_account(int n)
{
cust customers[n];
customers[n].acc_no = n;
printf("You are the customer number %d \n", customers[n].acc_no);
printf("Please, Enter your name: ");
scanf("%s", &customers[n].name);
printf("Please, Enter your age:");
scanf(" %d", &customers[n].age);
printf("Please, Enter your address: ");
scanf(" %s", &customers[n].address);
printf("Please, Enter your citizenship: ");
scanf(" %s", &customers[n].citizenship);
printf("Please, Enter your phone number: ");
scanf(" %f", &customers[n].phone);
printf("Please, Enter your account type: ");
scanf(" %s", &customers[n].acc_type);
}
>
Each of your three functions declares its own customers array variable, so each of them has their own memory for the customer data. Moreover, the array of new_account goes out of scope at the end of the function, so you can no longer safely access the data. Because of how C compilers typically work, the customer data is not immediately erased from memory, so your view_account function might still be able to read it, but that is what is called "undefined behavior". Which means it might work, or it might not.
Try to pass down the array from the main function to the other two functions in parameters. Or, to make things simpler at first, you could also turn the local customers variable of main into a global variable.
cust customers[10];
int main(int argc, char *argv[])
{
char answer;
int n;
int cutomer_number=1;
int cutomer_num2;
printf("Welcome To The program X: \n");
...
}
void view_account(int n) {
printf("Your name is %s \n ", customers[n].name);
...
}
void new_acccount(int n)
{
customers[n].acc_no = n;
...
}
Note that there are further issues in your code, like not checking the return value of scanf or overflowing the char arrays of the struct if you enter too many characters (missing bounds and length checking), or being able to enter more than 10 customers and accessing out of bounds of the customers array, or not using customers[0] (because your customer_number starts at 1, but array indices are 0-based). But I will not go into further details here to keep the answer focused.

String and for loop [duplicate]

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

The output not displaying after scanf() using c programming

Here im working on my first coding in c programming. I've got the problem when I want to get the user input and display the output from the user input. here my code:
#include <stdio.h>
int main(){
printf("Enter the number : ");
int hallo = 0;
scanf("%d", hallo);
printf("hallo, %d", hallo);
}
after executing the code the last line not appear where is prinf("hallo, %d", hallo);. Which is to display the user input.
The 4th line of the code: scanf("%d", hallo);
Here &hallo should be used instead of just the variable name hallo.
The significance of the & sign is that it gives the address of a particular variable. So whatever the value is entered by the user, it will be stored at the address of the variable (in this case at the address of variable hallo).
Use the & after the , in scanf
Like this
scanf("%d", & hallo);
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char name[30];
int id;
double salary;
} Employee;
int main()
{
int n;
printf("Number of employee to process: ");
scanf("%d",&n);
Employee employees[n];
printf("Enter %d Employee Details \n \n",n);
for(int i=0; i<n; i++){
printf("Employee %d:- \n",i+1);
printf("Name: ");
scanf("%[^\n]s",employees[i].name);
printf("Id: ");
scanf("%d",&employees[i].id);
printf("Salary: ");
scanf("%lf",&employees[i].salary);
char ch = getchar();
printf("\n");
}
printf("-------------- All Employees Details ---------------\n");
for(int i=0; i<n; i++){
printf("Name \t: ");
printf("%s \n",employees[i].name);
printf("Id \t: ");
printf("%d \n",employees[i].id);
printf("Salary \t: ");
printf("%.2lf \n",employees[i].salary);
printf("\n");
}
return 0;
}

Looping function on my int isMember()

#include <stdio.h>
int isMember();
float calculatePrice(int,int,int);
void printPlayer();
char name[4][100];
char name1[100];
int numofplayer, i, numofbook;
int member;
float game, discount, gst, subtotal, total;
int main()
{
i=0;
printf ("Your name: ");
gets (name1);
printf ("No of player: ");
scanf ("%d",&numofplayer);
while (i<numofplayer)
{
printf ("Enter Player %d: ",i+1);
scanf ("%s",name[i]);
i++;
}
printf ("How many game do you want to book?: ");
scanf ("%d",&numofbook);
isMember();
calculatePrice(isMember(),numofbook,numofplayer);
printf ("=======================\n");
printf ("Your booking detail.\n");
printf ("Your name is: %s",name1);
printf ("\nNo of player: %d",numofplayer);
printf ("\nList of player ");
printPlayer();
printf ("\nNo of game: %d",numofbook);
if (isMember()==1)
{
printf ("Status member: member \n");
}
else
{
printf ("Status member: not a member \n");
}
printf ("Total price is (including GST): %.2f",calculatePrice(isMember(),numofbook,numofplayer));
return 0;
}
int isMember()
{
printf ("Are you a member of this club?(1-yes or 0=no): ");
scanf ("%d",&member);
return member;
}
float calculatePrice(int a, int b, int c)
{
game=25;
subtotal=game*c;
subtotal=subtotal*b;
if (a==1)
{
discount=subtotal*0.1;
subtotal=subtotal-discount;
}
gst=0.06*subtotal;
total=subtotal-gst;
return total;
}
void printPlayer()
{
int i;
i=0;
while (i<numofplayer)
{
printf ("%d) ",i+1);
printf ("%s \n",name[i]);
i++;
}
}
Why did it loop at my isMember()?
It keeps looping over and over then it stops, and the other function I am not even confident if it runs correctly.
It doesn't loop.
Instead of keeping the returned value from isMember(), you called it over and over again.
You should define a new variable and save the result in it.
res = isMember();
and use res anywhere you called isMember().

Taking some string input from user with C

I am not too familiar with C syntax. I need to process some data based on user input. Although I processed the data successfully but I am stuck at user input section. I removed the unnecessary data processing section and made a simple example of how I am taking the user input. Can anyone tell me what's the problem with below code :
int i, number;
char *str;
str=(char*)malloc(1000*sizeof(char));
printf("Enter count : ");
scanf("%d", &number);
for(i=0; i<number; i++)
{
printf("\nEnter string: ");
scanf ("%[^\n]%*c", str);
printf("%s", str);
}
Output:
"Enter count : " appears fine, but whenever I provide some value and hit enter it's showing me only 'count' number of Enter string: without enabling user to enter the string.
For example -
Enter count : 2
Enter string:
Enter string:
But if I discard the count input section and provide any fixed value, like
for(i=0; i<5; i++)
it works fine
Thanks in advance
FYI, there is no issue in for(i=0; i<number; i++), problem is in scanning logic.
Actually, scanf ("%[^\n]%*c", str); is not right. you should use %s to read strings, not %c, which reads a single character, including the ENTER (newline).
Rather, i would suggest, use fgets() for inputs. It's a whole lot better in every way. Check the man page here.
Maybe you can use something like
//Dummy code
int i, number;
char *str;
printf("Enter count : ");
scanf("%d", &number);
str=malloc(number*sizeof(char)); //yes, casting not required
fgets(str, (number-1), stdin ); //"number" is used in different context
fputs(str, stdout);
EDIT:
Working code
#include <stdio.h>
#include <stdlib.h>
#define SIZ 1024
int main()
{
int i, number;
char * str = malloc(SIZ * sizeof (char));
printf("Enter the number :\n");
scanf("%d", &number);
getc(stdin); //to eat up the `\n` stored in stdin buffer
for (i = 0; i < number; i++)
{
printf("Enter the string %d :", (i+1));
fgets(str, SIZ-1, stdin);
printf("You have entered :");
fputs(str, stdout);
}
return 0;
}
scanf("%s",str); Use this instead of the code you are using to take string inputs in a character array.
There is a newline character \n after entering count value which is picked up by %c in your scanf()
Just use %s to scan strings as shown below.
scanf("%s",str);
If there are spaces in your input.
Then do
char c[50];
fgets(c,sizeof(c),stdin);
Check the below code:
#include <stdio.h>
#include<stdlib.h>
int main(){
int i, number;
char *str;
str=malloc(1000*sizeof(char));
printf("Enter count : ");
scanf("%d%*c", &number);
for(i=0; i<number; i++)
{
printf("\nEnter string: ");
fgets(str,1000,stdin);
printf("%s", str);
}
}

Resources