【问题标题】:Convert int to char array ("string")将 int 转换为 char 数组(“字符串”)
【发布时间】:2014-04-27 10:58:37
【问题描述】:

我是 C 新手。我有一个结构员工,如下所示:-

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

我想将此 eid 值分配为“EMP_1”、“EMP_2”等。每当任何员工输入其姓名时,其 id 都应动态生成,例如第一个员工的“EMP_1”和第二个员工的“EMP_2”。但我无法理解如何将整数值添加到 char 中。 我试过这样的

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;

但它不起作用。任何其他建议如何将“EMP_1”“EMP_2”等值分配给 struct 的 id。

【问题讨论】:

  • 1) 结构定义后缺少分号。 2) struct emp 是什么? 3) char[100] eid; -->> char eid[100];
  • @wildplasser struct employee 是一个员工类型的结构。

标签: c arrays string struct int


【解决方案1】:

使用snprintf()

snprintf(emp.eid, sizeof emp.eid, "%s%d", "EMP_", id);

【讨论】:

  • 在此之后emp.id的类型将是字符串类型?
  • 如果我们想打印它的值,那么我们将使用 printf("%s",emp.id); ??
  • emp.eid 始终具有 char [100] 类型。一旦这样定义,它就永远不会改变。要打印它,你的用法是正确的。
【解决方案2】:

当您定义字符串eid 相当大时,我认为使用sprintf 就足够了。

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);

【讨论】:

    猜你喜欢
    • 2016-08-13
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2016-08-14
    相关资源
    最近更新 更多