I wanted to create a program in c that reads the student name, roll number, marks of 3 subjects. when I run the program it is showing no errors, but the problem is whenever I try to input information it is taking only 2 inputs. Anyone please check the program and state the error in my program.
#include <stdio.h>
struct student
{
char sname[20];
int srollno;
int smarks[3];
};
int main ()
{
struct student e[3];
int i,j;
for (i=0;i<=2;i++)
{
scanf ("%s",e[i].sname);
scanf ("%d",e[i].srollno);
for (j=0;j<=2;j++)
{
scanf ("%d",e[i].smarks[j]);
}
}
}
it is taking only two inputs.
you have some problem in your scanf.
Try this:
scanf("%s",&e[i].sname);
I perform some little change on your code.
This is working version of code.
Code
#include <stdio.h>
struct student
{
char sname[20];
int srollno;
int smarks[3];
};
int main ()
{
struct student e[3];
int i,j;
for (i=0;i<=2;i++)
{
printf("Name: ");
scanf("%s", e[i].sname);
printf("roolNumber: ");
scanf("%d", &e[i].srollno);
for (j=0;j<=2;j++)
{
printf("Mark %d: ",j);
scanf("%d", &e[i].smarks[j]);
}
}
printf("\n\nprinting \n\n");
for (i=0;i<=2;i++)
{
printf("Name: %s\n", e[i].sname);
printf("roolNumber: %d\n", e[i].srollno);
for (j=0;j<=2;j++)
{
printf("Mark: %d\n", e[i].smarks[j]);
}
printf("\n");
}
}
Compile and Run
gcc -Wall source.c -o source
./source
I suggest to use printf() before try to scanf(), this makes User Interface better.
scanf() char array don't need & (address) operator. see this
char str[10];
scanf("%s", str);
printf("%s\n", str);
Work exactly like
char str[10];
scanf("%s", &str[0]);
printf("%s\n", str);
Because str is pointer to its first elementstr[0]. As stated in link we can write printf("%d\n", str==&str[0]); and always the result is one that show str and &str[0] are identical.
Related
So I have this super simple C code here taking a user input and prints it out followed by a "T-Plus" while loop. In this case I chose a random name for testing "whoa", but the while loop is not called. My question is, why does the "T-Plus: %d\n" while loop print not be called after the printf() function?:
#include <stdio.h>
char getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
printf("%s", getString());
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char getString()
{
char name;
printf("Please a string name: \n");
scanf("%s", &name);
return name;
}
Now when I run it, this becomes the output:
$ ./namecount
Please a string name:
whoa
but the T-Plus: string does not get called.
I see two issues here:
1) In function getString() you are trying to read/scan a string in a char, you need memory to store the string and a terminating char, so you can use either of these two ways
Use a char array e.g. char name[50]; or
Use a char pointer and
allocate memory using malloc e.g.
char *p_name = malloc(sizeof(char)*50);
2) You are then trying to return this string which is stored in local variable (which would get destroyed as soon as function ends) so you should use the second approach (use malloc) and return the pointer.
So your code would look like:
#include <stdio.h>
#include <stdlib.h>
char * getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
char *p_name = getString();
printf("%s", p_name);
free(p_name);
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char *getString()
{
char *p_name = malloc(sizeof(char)*50);
printf("Please a string name: \n");
scanf("%s", p_name);
return p_name;
}
Above answer did not work, Okay so I've edited the code like this, it compiles fine. But raises a segmentation fault though.
#include <stdio.h>
#include <stdlib.h>
char * getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
char *name = getString();
printf("%s", name);
free(name);
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char * getString()
{
char *p_name[50];
printf("Please a string name: \n");
scanf("%49s", (char *) &p_name);
return *p_name;
}
When the program is run, it asks for your input but still raises a Segmentation fault (core dumped).
I'm writing a code that uses a function to return a pointer to a struct, which is allocated dynamically. However, my code isn't reading strings. When I run it, it simply jumps the "Type name" part, I type the age, and it prints the age and nothing for the name. Strangely, the code works when I use scanf to read the string, but it didn't with gets or fgets. Could anyone please help me? Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
struct details
{
char name[100];
int age;
};
struct details * details_pointer(int n)
{
struct details *pointer = (struct details *) malloc (n*sizeof(struct details));
for (int i=0; i<n; i++)
{
printf("Student %d:\n", i);
printf("name:\n");
scanf("%s", pointer[i].name);
//gets(pointer[i].name); not working
//fgets(pointer[i].name, 100, stdin); not working
printf("age:\n");
scanf("%d", &pointer[i]. age);
}
return pointer;
}
int main()
{
int n;
printf("Type the number of persons:\n");
scanf("%d", &n);
struct details *student = details_pointer(n);
for (int i=0; i<n; i++)
{
printf("\nName: %s", (*(student+i)).name);
printf("Age: %d\n", (*(student+i)).age);
}
free(student);
system("pause");
return 0;
}
This is because scanf leaves a newline in the input stream. fgets gets it as the name when it is called. To prove this, change:
scanf("%d", &n);
to something like:
n = 1;
and you will see no problem.
If you don't want to use scanf, you can call fgets then atoi/strtol.
char *num;
fgets(num, 100, stdin);
n = atoi(num);
After I execute the exe I get this error :
undefined reference to `StudentScan'
error: ld returned 1 exit status|
Note: I'm bad and new to coding so don't mind my bad coding please^^
Note2: I'm just messing with random functions.
#include <stdio.h>
#include <stdlib.h>
struct student {
char firstName[20];
char AverageNum[2];
};
void StudentScan(int, struct student[]);
void StudentPrint(int, struct student[]);
int main() {
int i;
int length;
struct student *studentp;
printf ("\nEnter the host of students: ");
scanf ("%d ", &length);
struct student list[length];
studentp=malloc(length*sizeof(struct student));
if (studentp==NULL)
{
printf("Out of memory!");
return 0;
}
for(i = 0; i < length; i++) {
StudentScan(i,studentp);
printf("\nEnter average number: ");
scanf("%s", list[i].AverageNum);
}
free (studentp);
void StudentScan(int i, struct student list[])
{ printf("\nEnter first name : ");
scanf("%s", list[i].firstName);
printf("\nEnter average number: ");
scanf("%s", list[i].AverageNum);
}
return 0;
}
The posted code has defined StudentScan() within main(). But nested function definitions are not allowed in C. This should generate a compiler warning, such as:
warning: ISO C forbids nested functions [-Wpedantic]
void StudentScan(int i, struct student list[])
Pay attention to all compiler warnings and fix them. If no warning is seen when compiling this code, turn up the level of compiler warnings. On gcc, I suggest to always use at least gcc -Wall -Wextra, and I always add -Wpedantic. The -Wpedantic is needed with gcc to see a warning for this. Some compilers, and gcc is one of these, do support nested function definitions as a compiler extension. Still, this feature is nonstandard, and it is best to not rely on it.
The fix is simple: move the definition of StudentScan() out of main():
#include <stdio.h>
#include <stdlib.h>
struct student {
char firstName[20];
char AverageNum[2];
};
void StudentScan(int, struct student[]);
void StudentPrint(int, struct student[]);
int main(void) {
int i;
int length;
struct student *studentp;
printf ("\nEnter the host of students: ");
scanf ("%d ", &length);
struct student list[length];
studentp=malloc(length*sizeof(struct student));
if (studentp==NULL)
{
printf("Out of memory!");
return 0;
}
for(i = 0; i < length; i++) {
StudentScan(i,studentp);
printf("\nEnter average number: ");
scanf("%s", list[i].AverageNum);
}
free (studentp);
return 0;
}
void StudentScan(int i, struct student list[])
{ printf("\nEnter first name : ");
scanf("%s", list[i].firstName);
printf("\nEnter average number: ");
scanf("%s", list[i].AverageNum);
}
Also note that you should always specify maximum widths when reading strings using scanf() family functions with %s or %[] to avoid buffer overflow. For example:
scanf("%19s", list[i].firstName);
Note that 19 is used, even though the firstName field is an array of 20 char values. Remember that one space must be reserved for the \0 terminator. And since you are using %s to read a string into the AverageNum field, you should also have:
scanf("%1s", list[i].AverageNum);
That is, this field can only hold one digit. If the intention is to hold two digits, this field must be changed within the struct to: char AverageNum[3].
And while we are discussing scanf(), note that this function returns the number of successful assignments made during the function call. If no assignments are made, 0 is returned. This return value should always be checked. Consider: if the user mistakenly enters a letter when a digit is expected, nothing is stored in the intended variable. This may lead to undefined behavior. You may try something like this to validate numeric input:
printf ("\nEnter the host of students: ");
while (scanf ("%d ", &length) < 1) {
puts("Please enter a number");
int c;
while ((c = getchar()) != '\n' && c != EOF) {
continue;
}
}
This code asks the user to enter input again if a number is not entered when expected. Note that if the user does enter a non-digit, this character remains in the input stream and must be cleared before attempting to process more user input. The while loop is a typical construction which accomplishes this task.
Edit
Based on comments made by the OP, here is a modified version of the posted code. This version uses a float value instead of a character array for the AverageNum field of the struct. A floating-point type may be more useful than an integer type for storing averages. It is usually best to use double for floating-point values, but in this case it looks like AverageNum has little need for precision (the char array was intended to hold only two digits); float is probably sufficient for this use. If a different type is desired, it is simple enough to modify the code below.
Some input validation is implemented, but note that more could be done. The user is prompted to enter a number when non-numeric input is found where numeric input is expected. The input stream is cleaned with the while loop construction after such an input mistake; it would be good to remove this code to a separate function called clear_input(), for example.
If the user signals end-of-file from the keyboard, scanf() will return EOF; the code below chooses to exit with an error message rather than continue with malformed input in this case. This could also occur with input redirected from a file, and this condition may need to be handled differently if such input is expected.
The loop that populated the list[] array seemed to be operating inefficiently, asking for AverageNum twice in each pass. This has been streamlined.
Note that the call to malloc() can be rewritten as:
studentp = malloc(length * sizeof *studentp);
This is a very idiomatic way of writing such an allocation. Here, instead of using an explicit type as the operand of sizeof, that is, instead of sizeof (struct student), the variable which holds the address of the allocation is used. sizeof only uses the type of the expression *studentp, so this variable is not dereferenced here. Coding this way is less error-prone and easier to maintain when types change during the maintenance life of the code.
Yet, it is unclear why memory is allocated for studentp in the first place. In the posted code, both the firstName and AverageNum fields are filled for members of the dynamically allocated studentp in calls to StudentScan() in a loop; the same loop fills the AverageNum field of the members of list[] (a different array of structs) with different input. There seems to be no need for one of these arrays of student structs; I have commented-out the dynamically allocated array in favor of the statically allocated version.
Here is the modified code:
#include <stdio.h>
#include <stdlib.h>
struct student {
char firstName[20];
float AverageNum;
};
void StudentScan(int, struct student[]);
void StudentPrint(int, struct student[]);
int main(void) {
int i;
int length;
// struct student *studentp;
printf ("\nEnter the host of students: ");
while (scanf ("%d", &length) < 1) {
puts("Please enter a number");
int c;
while ((c = getchar()) != '\n' && c != EOF) {
continue;
}
}
struct student list[length];
/* This is fine */
// studentp = malloc(length * sizeof (struct student));
/* But this is better */
// studentp = malloc(length * sizeof *studentp);
// if (studentp == NULL)
// {
/* Not wrong, but... */
// printf("Out of memory!");
// return 0;
// fprintf(stderr, "Allocation failure\n");
// exit(EXIT_FAILURE);
// }
for(i = 0; i < length; i++) {
StudentScan(i, list);
}
/* Code to display results here */
// free (studentp);
return 0;
}
void StudentScan(int i, struct student list[])
{
putchar('\n');
printf("Enter first name: ");
if (scanf("%19s", list[i].firstName) != 1) {
puts("Input error");
exit(EXIT_FAILURE);
}
printf("Enter average number: ");
while (scanf("%f", &list[i].AverageNum) < 1) {
puts("Please enter a number");
int c;
while ((c = getchar()) != '\n' && c != EOF) {
continue;
}
}
}
You have to remove the scan function from the main. Also there is not a printstudent function you are declaring. You must remove /n from the printf and the scanf functions and place them accordingly. You can then test if your data are being added correctly in your struct with a simple loop.
#include <stdio.h>
#include <stdlib.h>
struct student {
char firstName[20];
char AverageNum[2];
};
int main() {
int i=0;
int length;
struct student *studentp;
printf ("Enter the host of students:");
scanf ("%d", &length);
struct student list[length];
studentp=malloc(length*sizeof(struct student));
if (studentp==NULL)
{
printf("Out of memory!");
return 0;
}
for(i = 0; i < length; i++) {
printf("Enter first name :");
scanf("%s", list[i].firstName);
printf("Enter average number: ");
scanf("%1s", list[i].AverageNum);
}
for(i = 0; i< length; i++){
printf("number of host is: %d , his/her first name: %s , his/her avg number: %s \n", i, list[i].firstName, list[i].AverageNum);
}
free (studentp);
return 0;
}
My main goal for this code is to capture the users input and do whatever he wants to do with the choices I have presented, but I'm stuck: when I compile, I can only type the word and the program stops working.
i have no idea where I'm making a mistake.
The is my code:
#include <stdio.h>
#include <string.h>
#define MAX_STRING_LENGTH 100
void grab_user_input(void);
void load_menu(void);
void Count_the_letters(void);
int main(void)
{
grab_user_input();
return 0;
}
void grab_user_input(void)
{
char word;
{
printf("Please enter a single word (25 characters or less): \n");
scanf("%s", &word);
printf("Thanks! The word you entered is: %s\n", word);
}
void load_menu(void)
{
int choice;
do
{
int choice;
printf("\n(:===Menu====:)\n");
printf("1. Count_the_letters\n");
printf("2. Count_the_vowels\n");
printf("3. Reverse_the_word\n");
printf("4. Check_if_palindrome\n");
printf("5. Enter_a_new_word\n");
printf("6. Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1: Count_the_letters();
break;
}
} while (choice != 3);
}
void Count_the_letters(void)
{
char S[MAX_STRING_LENGTH];
int count;
count = 0;
do {
printf("string:\t");
scanf("%s",S);
if (strcmp(S,"exit") != 0)
++count;
} while (strcmp(S,"exit") != 0);
printf("word count:\t%d\n", count);
}
return 0;
}
scanf("%s", &word);
needs an array of characters to read the data. &word only has space for one character.
You are running into undefined behavior.
Use
char word[26];
scanf("%25s", &word);
The reason is that you are passing the address to the char variable you declared and scanf() is trying to write two bytes where it only fits one.
char word
this declares a char variable, it can hold a single byte
scanf("%s", &word);
whill require at least one byte for an empty string the '\0'.
But also, you declared a lot of functions inside void grab_user_input(void), that is not valid standard c, it might work with some compiler, but it's not standard.
I am just learning C and making a basic "hello, NAME" program. I have got it working to read the user's input but it is output as numbers and not what they enter?
What am I doing wrong?
#include <stdio.h>
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%d", &name);
printf("Hi there, %d", name);
getchar();
return 0;
}
You use the wrong format specifier %d- you should use %s. Better still use fgets - scanf is not buffer safe.
Go through the documentations it should not be that difficult:
scanf and fgets
Sample code:
#include <stdio.h>
int main(void)
{
char name[20];
printf("Hello. What's your name?\n");
//scanf("%s", &name); - deprecated
fgets(name,20,stdin);
printf("Hi there, %s", name);
return 0;
}
Input:
The Name is Stackoverflow
Output:
Hello. What's your name?
Hi there, The Name is Stackov
#include <stdio.h>
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%s", name);
printf("Hi there, %s", name);
getchar();
return 0;
}
When we take the input as a string from the user, %s is used. And the address is given where the string to be stored.
scanf("%s",name);
printf("%s",name);
hear name give you the base address of array name. The value of name and &name would be equal but there is very much difference between them. name gives the base address of array and if you will calculate name+1 it will give you next address i.e. address of name[1] but if you perform &name+1, it will be next address to the whole array.
change your code to:
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%s", &name);
printf("Hi there, %s", name);
getchar();
getch(); //To wait until you press a key and then exit the application
return 0;
}
This is because, %d is used for integer datatypes and %s and %c are used for string and character types