Domanda

I am new to C. I have a struct employee like follows:-

struct employee
{
    char eid[100];
    char name[100];
};

I want to assign this eid value as "EMP_1", "EMP_2" and so on. Whenever any employee enters its name its id should be generated dynamically like "EMP_1" for the first employee and "EMP_2" for the second employee. But i am not able to understand how to add an integer value to a char. I have tried like this

struct employee e;
char emp[20]="EMP_";
char id=(char)i; //Here i will be representing the number of employee like 1st or 2nd.
strcat(emp,id);
e.id=emp;

But it is not working. Any other suggestions how to assign "EMP_1" "EMP_2" etc value to id of struct.

È stato utile?

Soluzione 2

As you define string eid quite large, I think using sprintf is simply enough.

struct employee e;
int id=1; //Here i will be representing the number of employee like 1st or 2nd.
sprintf(e.eid,"EMP_%d",id);

Altri suggerimenti

Use snprintf().

snprintf(emp.eid, sizeof emp.eid, "%s%d", "EMP_", id);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top