Reputation: 53
I'm trying to put in upper case a first letter in a name. Something does not work. Also, I want to put whole surname in upper case. Which doesn't work too. Somehow only the first letter(of the above mentioned) get an upper case.
I have this code, and it does not work as expected:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct Student
{
char name[50];
char surname[50];
int year_of_birth;
};
void display(struct Student array[],int size);
int main()
{
int n;
printf("enter number: ");
scanf("%d",&n);
struct Student* array = malloc(n*sizeof(array));
for(int i=0; i<n; i++)
{
printf("enter name: ");
scanf(" %[^\n]*c",array[i].name);
printf("enter surname: ");
scanf(" %[^\n]*c",array[i].surname);
printf("enter birth year: ");
scanf(" %d",&array[i].year_of_birth);
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
array[i].surname[j] = toupper(array[i].surname[j]);
array[i].name[0] = toupper(array[i].name[0]);
if(isspace(array[i].name[j]))
array[i].name[j+1] = toupper(array[i].name[j+1]);
}
}
puts("");
puts("::SHOWING::");
display(array,n);
return 0;
}
void display(struct Student array[],int size)
{
for(int i=0; i<size; i++)
{
printf("Student info %d: %s %s %d \n",i+1,array[i].name,array[i].surname,array[i].year_of_birth);
}
}
The output:
enter number: 2
enter name: olivia emma
enter surname: james
enter birth year: 2000
enter name: john noah
enter surname: Smith
enter birth year: 2002
::SHOWING:: Student info 1: Olivia emma JAmes 2000 Student info 2: John noah SMith 2002
Expected output:
Student info 1: Olivia Emma JAMES 2000 Student info 2: John Noah SMITH 2002
Upvotes: 0
Views: 64
Reputation: 311068
For starters you are allocating a memory of an invalid size
struct Student* array = malloc(n*sizeof(array));
It seems you mean
struct Student* array = malloc(n*sizeof(*array));
In these calls of scanf
scanf(" %[^\n]*c",array[i].name);
printf("enter surname: ");
scanf(" %[^\n]*c",array[i].surname);
the conversion specifiers *c are redundant. White space characters will be skipped in any case due to leading spaces in the format strings. So you could write
scanf(" %49[^\n]",array[i].name);
printf("enter surname: ");
scanf(" %49[^\n]",array[i].surname);
For the data member surname
you could use a loop as for example
for ( char *p = array[i].surname; *p != '\0'; ++p )
{
*p = toupper( ( unsigned char )*p );
}
For the data member name you could use another loop
#include <string.h>
//...
for ( char *p = array[i].name; *p != '\0'; p += strspn( p, " \t" ) )
{
*p = toupper( ( unsigned char )*p );
p += strcspn( p, " \t" );
}
Upvotes: 1