Printing with structure - c

This is a program for preparing simple student marklist:
#include <stdio.h>
#include <conio.h>
#define SIZE 50
struct mark {
char name[50];
float marks[5];
};
int main() {
int sn, subn, i, j;
printf ("\n Enter Number of Students : ");
scanf ("%d",&sn);
printf ("\n");
struct mark n[SIZE];
for (i = 1; i < sn + 1; ++i){
printf (" Enter Name of Student %d : ",i);
scanf ("%s",&n[i - 1].name);
for (j = 1; j < 6; ++j){
printf (" Enter Marks of Subject %d : ",j);
scanf ("%f",&n[i - 1].marks[j - 1]);
}
}
printf ("\n\n ------------------------------------------------------------------- \n\n");
printf (" Student Name \t\t Sub 1\t Sub 2\t Sub 3\t Sub 4\t Sub 5");
printf ("\n --------------------------------------------------------------------\n");
for (i = 0; i < sn; ++i) {
printf ("\n %s \t\t ",n[i].name);
for (j = 0; j < subn; ++j){
printf ("%d \t",n[i].marks[j]); /* Problem with this line. Prints integers like -24611 etc.*/
}
}
getch();
return 0;
}
When I get to the marked line, the program prints some numbers like -241563 etc.
What's wrong? Is it something with the structure? First it prints five 0 when it would have printed the marks. And then prints the integers like -241563. Please help.

The format string in printf does not match the argument list
Change:
printf("%d \t", n[i].marks[j]);
to
printf("%f \t", n[i].marks[j]);

Related

Why can't I print all the character types of variables in array?

#include <stdio.h>
#include <conio.h>
int main() {
char name[20];
int age[20], i, size;
printf("Enter number of students: ");
scanf("%d", &size);
for (i = 0; i < size; i++)
{
printf("\nEnter Student # %d name: ", i+1 );
scanf("%s", &name[i]);
printf("\nEnter Student # %d age: ", i+1 );
scanf ("\n%d", &age[i]);
}
printf("---");
printf("\n Student Information");
for (i = 0; i < size; i++)
{
printf("\nStudent # %d :\n", i+1);
printf("Name: %c", name[i]); //how do i print the array here?
printf("\nAge: %d", age[i]);
}
return 0;
}
For some reason, I can't display the whole characters that are inputted, and instead, my program produces nothing. What's causing this and how can I fix it?
starboy_b already answered your question, but I want to highlight security issues in your code:
Keep in mind that using scanf to get input like you do is introducing dangerous vulnerabilities to your program.
Why? :
scanf does not know how much allocated space your variables have and does not prevent the user from entering more characters than your buffer can contain. This lead to buffer overflow and can be used to run attacker code.
Your better off e.g. using readline or fgets to get input from user.
#include <stdio.h>
#include <conio.h>
int main() {
char name[20][100];
int age[20], i, size;
printf("Enter number of students: ");
scanf("%d", &size);
for (i = 0; i < size; i++)
{
printf("\nEnter Student # %d name: ", i+1 );
scanf("%s", &name[i]);
printf("\nEnter Student # %d age: ", i+1 );
scanf ("\n%d", &age[i]);
}
printf("---");
printf("\n Student Information");
for (i = 0; i < size; i++)
{
printf("\nStudent # %d :\n", i+1);
printf("Name: %s", name[i]); //how do i print the array here?
printf("\nAge: %d", age[i]);
}
return 0;

Wrong Results Being Printed in C After Being Inserted in 2D Char Array

int const size = 100;
float grades[size];
char students[size][size];
char temp_students[size][size];
int main() {
int length = 0;
int i = 0;
float g = 0;
printf("How many students do you want to enter? \n ");
scanf("%d", &length);
while((i < length)){
printf("Enter the name and grade \n");
// scanf("%s", students[i]);
char temp;
scanf("%c",&temp); // temp statement to clear buffer
scanf("%[^\n]", students[i]);
strcpy(temp_students[i], students[i]);
printf("Enter the grade again \n");
scanf(" %f", &g);
grades[i] = g;
insertion_sort_float(grades, g, length);
insertion_sort_string(students, students[i], length);
i++;
}
i--;
print_report(grades, students, length);
}
void print_report(float grades[], char students[size][size], int number){
printf("Students Test Report \n");
printf("Students that took the test: %d \n", number);
for (int i = 0; i < number; i++){
for(int j = 0; j < number; j++){
printf("%c", students[i][j]);
}
printf("\n");
}
double average = average_number(grades, number);
double median = median_number(grades, number);
double highest = max_number(grades, number);
double lowest = min_number(grades, number);
printf("Average: %f \n Median: %f \n Highest: %f \n Lowest: %f \n", average, median, highest, lowest);
}
void insertion_sort_string(char students[size][size], char string[], int array_size) {
if (array_size+ 1 < size) {// only do insert when there is free space in array
if (array_size == 0)//empty array, insert at the top directly
strcpy(students[0], string);
int insert_index;//to identify the location
for (int i = 0; i < array_size + 1; i++) {
insert_index = i;
if (strcmp(students[i], string)) // due the sorted property of array,
break;// where the first bigger item showes up, where we should insert    
}//end of the first for loop
// if we don't find any bigger item, inset_index will equal to element_num, which means we insert at the tail
for (int j = array_size; j > insert_index; j--) {
strcpy(students[j], students[j-1]);
}// end of the second loop
strcpy(students[insert_index], string); // do the insert    
} else {
printf("overflow!");
return;
}
}
This is what happens when the code is run:
Write a program that allows a user to enter the names of students that took a test along with the grades they received.
I am not sure why none of the other names are being stored. Only Gerar is being printed. Also the entire string should be printed: "Gerard 78.5", but that is not happening either.
Some code omitted for post purposes. But important code is included

C Print Data from loop after loop ends

So, I managed to wrangle some code to get part of my program working. My program has to have a prompt to enter grades (done), repeat in a loop until broken (doneish), and print results of each grade entered. The last part is where I am stuck. I can't seem to find a good way to get any grade I entered to print at the end. I just want a "you entered ###, ###, ###," or something similar, but it can be up to 100 numbers. Below is what I have so far
#include <stdio.h>
#define MAX_ARRAY_SIZE 100
int main(void) {
int grade[MAX_ARRAY_SIZE];
int entryCount = 0;
char continueResponse;
printf("Enter an grade of between 1 and 100. \n");
printf("Enter a maximum of %d grades. \n", MAX_ARRAY_SIZE);
int i;
for(i = 0; i < MAX_ARRAY_SIZE; i++) {
printf("Enter grade: ");
scanf("%d", &grade[i]);
printf("Continue? (y/n): ");
scanf(" %c", &continueResponse);
entryCount++;
if(continueResponse == 'n' || continueResponse == 'N') {
printf(" == End of Data Entry ==\n\n");
break;
}
}
return 0;
}
Keep in mind this is third week of doing this, so I know next to nothing. If there's a "why did you do this like this", the answer is because that's how I've done it before and it works. I appreciate any input!
After your dataentry loop:
for(i = 0; i < MAX_ARRAY_SIZE; i++) {
...
}
You just have to add a second loop:
for(i = 0; i < entryCount; i++) {
printf ("%d ", grade[i]);
}
You've recorded entryCount entries to the array, numbered 0 ... entryCount - 1; you'd use another for loop to print them. For nicer formatting we do not print ", " after the last number:
printf("You've entered ");
for (i = 0; i < entryCount; i++) {
if (i == entryCount - 1) {
printf("%d", grade[i]);
}
else {
printf("%d, ", grade[i]);
}
}
printf("\n");
what I understood about your problem the following code would work:
#include <stdio.h>
#define MAX_ARRAY_SIZE 100
int main(void) {
int grade[MAX_ARRAY_SIZE];
int entryCount = 0;
char continueResponse;
printf("Enter an grade of between 1 and 100. \n");
printf("Enter a maximum of %d grades. \n", MAX_ARRAY_SIZE);
int i;
for(i = 0; i < MAX_ARRAY_SIZE; i++) {
printf("Enter grade: ");
scanf("%d", &grade[i]);
printf("Continue? (y/n): ");
scanf(" %c", &continueResponse);
entryCount++;
printf("you entred:\n");
for(int j=0;j<entryCount;j++)
{
printf("%d ",grade[j]);
}
if(continueResponse == 'n' || continueResponse == 'N') {
printf(" == End of Data Entry ==\n\n");
break;
}
}
return 0;
}

C Program - Don't know why it isn't working

The assignment is to create a program that lets the user enter student names and grades, list the input once all entries have been made, then calculate the average for all grades entered. The program uses structures and loops.
The code I have so far is below. It builds without any errors. However, after I enter the first set of "first name, last name, grade" and hit Enter, the program just sits there with a blinking cursor. I can't seem to figure out what I'm doing wrong.
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 50
// Structure to hold student names and grades
struct student
{
char firstName[MAX_LENGTH];
char lastName[MAX_LENGTH];
int grade;
};
int main ()
{
int i, j, num_students;
int sum = 0;
int cnt = 0;
// Determine how many students will be entered
printf ("Enter the number of students in your class: \n");
scanf ("%d", num_students);
// Obtain student names and grades
printf ("Enter first name, last name and grade separated by spaces. \n");
printf ("Enter END 0 when done entering information.\n\n");
struct student s[num_students];
for (i = 0; i < num_students; ++i) {
scanf ("%s %s %d", s[i].firstName, s[i].lastName, s[i].grade);
if(strcmp(s[i].firstName, "END") == 0) {
break;
}
}
// List students and grades entered
printf ("\nYou entered: \n");
for (j = 0; j < num_students; ++j){
if(strcmp(s[j].firstName, "END") == 0){
break;
}
printf("Name: %s %s, Grade: %d\n", s[i].firstName, s[i].lastName, s[i].grade);
}
// Calculate average of grades entered
for (i = 0; i < num_students; ++i)
{
if (strncmp(s[i].firstName, "END", 3) == 0){
break;
}
else {
sum += s[i].grade;
++cnt;
}
}
printf ("Average of Grades: %f\n", (float)sum/cnt);
return 0;
}
Change
printf("Name: %s %2, Grade: %d\n", s[i].firstName, s[i].lastName, &s[i].grade);
^ Wrong specifier ^ i should be j
to
printf("Name: %s %s, Grade: %d\n", s[j].firstName, s[j].lastName, s[j].grade);
Fix the '%2 bug and pass s[i].grade not &s[i].grade
This works for me: I added a line just after inserting the values for quick feedback
#include <stdio.h>
#include <string.h>
#define MAX_ENTRIES 20
#define MAX_LENGTH 50
// Structure to hold student names and grades
struct student
{
char firstName[MAX_LENGTH];
char lastName[MAX_LENGTH];
int grade;
};
int
main ()
{
int i, j;
int sum = 0;
int cnt = 0;
//Obtain student names and grades
printf ("Enter first name, last name and grade separated by spaces. \n");
printf ("Enter END 0 when done entering information.\n\n");
struct student s[MAX_ENTRIES];
for (i = 0; i < MAX_ENTRIES; ++i)
{
scanf ("%s %s %d", s[i].firstName, s[i].lastName, &s[i].grade);
printf ("Name: %s %s, Grade: %d\n", s[i].firstName, s[i].lastName,
s[i].grade);
if (strcmp (s[i].firstName, "END") == 0)
{
break;
}
}
//List students and grades entered
printf ("\nYou entered: \n");
for (j = 0; j < MAX_ENTRIES; ++j)
{
if (strcmp (s[j].firstName, "END") == 0)
{
break;
}
printf ("Name: %s %s, Grade: %d\n", s[j].firstName, s[j].lastName,
s[j].grade);
}
//Calculate average of grades entered
for (i = 0; i < MAX_ENTRIES; ++i)
{
if (strncmp (s[i].firstName, "END", 3) == 0)
{
break;
}
else
{
sum += s[i].grade;
++cnt;
}
}
printf ("Average of Grades: %f\n", (float) sum / cnt);
return 0;
}
Change this line (line no. 42)
printf("Name: %s %2, Grade: %d\n", s[i].firstName, s[i].lastName, &s[i].grade);
to this
printf("Name: %s %s, Grade: %d\n", s[j].firstName, s[j].lastName, s[j].grade);
I think it will help you :)
Append the code as ,
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 50
// Structure to hold student names and grades
struct student
{
char firstName[MAX_LENGTH];
char lastName[MAX_LENGTH];
int grade;
};
int main ()
{
int i, j, num_students;
int sum = 0;
int cnt = 0;
// Determine how many students will be entered
printf ("Enter the number of students in your class: \n");
scanf ("%d", &num_students);
// Obtain student names and grades
printf ("Enter first name, last name and grade separated by spaces. \n");
printf ("Enter END 0 when done entering information.\n\n");
struct student s[num_students];
for (i = 0; i < num_students; ++i) {
scanf ("%s %s %d", s[i].firstName, s[i].lastName, &s[i].grade);
if(strcmp(s[i].firstName, "END") == 0) {
break;
}
}
// List students and grades entered
printf ("\nYou entered: \n");
for (j = 0; j < num_students; ++j){
if(strcmp(s[j].firstName, "END") == 0){
break;
}
printf("Name: %s %s, Grade: %d\n", s[j].firstName, s[j].lastName, s[j].grade);
}
// Calculate average of grades entered
for (i = 0; i < num_students; ++i)
{
if (strncmp(s[i].firstName, "END", 3) == 0){
break;
}
else {
sum += s[i].grade;
++cnt;
}
}
printf ("Average of Grades: %f\n", (float)sum/cnt);
return 0;
}
Appended line 23 scanf ("%d", &num_students);
line 32 scanf ("%s %s %d", s[i].firstName, s[i].lastName, &s[i].grade);
line 46 printf("Name: %s %s, Grade: %d\n", s[j].firstName, s[j].lastName, s[j].grade);
Missed address operator in scanf argument twice:
scanf( "%d", &num_students );
/* .. */
scanf( "%s %s %d", s[i].firstName, s[i].lastName, & s[i].grade );
And index of previous loop was used instead of actual at printing array:
printf("Name: %s %s, Grade: %d\n", s[j].firstName, s[j].lastName, s[j].grade);
Handling "END"s is unneccessary when prompting for num_students. Just a suggestion: even loop variable names should be longer than a character. And feel free using double at floating point division unless you miss FPU.

program crashing using 2D dynamic string array in c

I am having a problem with this code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int num=0;
printf("Enter number of entries: ");
scanf_s("%d", &num);
char **firstname=NULL;
char **lastname=NULL;
float *score=NULL;
int i;
firstname = malloc(num * (sizeof(char*)));
for (i = 0; i < num; i++)
{
firstname[i] = malloc(21);
}
lastname = malloc(num * (sizeof(char*)));
for (i = 0; i < num; i++)
{
lastname[i] = malloc(21);
}
score = ((float*)malloc(num* (sizeof(float))));
for (i = 1; i <= num; i++)
{
printf("Enter the first name of entry %d: \n", i);
scanf_s("%s", firstname[i], 21);
printf("Enter the last name of entry %d: \n", i);
scanf_s("%s", lastname[i], 21);
printf("Enter the score of entry %d: \n", i);
scanf_s("%f", score[i]);
}
for (i = 0; i < num; ++i)
{
printf("%s, %s, %f", firstname[i], lastname[i], score[i]);
}
return 0;
}
I have edited the code with the suggested changes, and now it prints random characters and a random value for the first and last name, as well as the score. the code also crashes if there is more than one iteration of input (after asking for the score of the first entry, it crashes before asking for the first name of the second entry.)

Resources