I tried to make a userdata where it's declared as a struct. I tried to use scanf, but everytime i tried to compile it always says "expected expression before 'userdata'.
Anyone know how to fix this? Thank you
Here's my code:
#include <stdio.h>
typedef struct { char name[30]; char age[2]; char country[10]; char date[40];
} userdata;
int main()
{
printf("Please input your name: \n");
scanf("%c", &userdata.name);
printf("Please input your age: \n");
scanf("%c", &userdata.age);
printf("Which country are you from: \n");
scanf("%c", &userdata.country); printf("Please tell me the date of your birth in number format (00 - 00 - 0000)\n");
scanf("%c", &userdata.date);
printf("Here's your userdata: \n");
printf("Name : %c\n", userdata.name);
printf("Age : %c\n", userdata.age);
printf("Country : %c\n", userdata.country);
printf("Date of birth : %c\n", userdata.date);
return 0;
}
CodePudding user response:
You created a type called userdata
so now you need to declare an instance of the type to use it:
userdata u;
then you pass the address of the instance:
scanf("%c", &u.name);
CodePudding user response:
By using the typedef
keyword, you've declared userdata
as a type alias for a struct
. It's not a variable name.
If you remove the typedef
keyword, you'll declare a variable with that name.
Also, you need to use the %s
format specifier to read and write strings. The %c
format specifier is used for single characters. Also, since strings are terminated by a null byte, the age
member of your struct should be longer.
CodePudding user response:
You are trying to assign a value to a TYPE, not a variable. When you define typedef
, you do not create a variable, you create an alias for the type.
Let's say you have the int
type, but you don't like it being called int
. Then you can do typedef
and name the type int as you want:
typedef int MyType; // Create an alias for an int type
You do NOT create a variable of this type.
Your solution is to create a variable of userdata
and set it to:
userdata data;
scanf("%s", &data.name);
In addition, as @dbush rightly noted, you need to use the %s
specifier to read strings: the %c
specifier is used only for single characters.