【问题标题】:Copying Integer Value From Char Pointer to Local Variable in C将整数值从字符指针复制到 C 中的局部变量
【发布时间】:2015-12-30 04:14:50
【问题描述】:

我有一个字符串,我使用 strtok 将其分解为多个片段

    d.dtype = strtok(incoming.mtext, "|");
    d.threshold= strtok(NULL, "|");
    d.pid = strtok(NULL, "|");  

使用

    printf("device type %s\n", d.dtype);
    printf("device threshold %s\n", d.threshold);
    printf("device pid %s\n", d.pid);

我可以看到所有内容都已正确分配。

然后我正在发送一条外发消息,我的消息结构是

struct msg_st {
    long int mtype;
    char mtext[BUFSIZ];
};

struct msg_st outgoing; 

如何将d.pid 值复制到我的outgoing.mtype 中?

【问题讨论】:

  • outgoing.mtype = strtol(d.pid, NULL, 10);

标签: c pointers copy message-queue


【解决方案1】:

您可以使用来自<stdlib.h> 的atoi 从char * 中提取int 值

outgoing.mtype = atoi(d.pid);

【讨论】:

  • 我可以发誓我试过了,但它给了我一个错误,虽然它似乎有效,谢谢。
  • 很高兴知道。不要忘记单击接受答案按钮。谢谢!
【解决方案2】:

要将字符串值转换为long int,可以使用

outgoing.mtype = atol(d.pid);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2013-10-03
    相关资源
    最近更新 更多