我想让他拼接数值
#include "stdio.h"
#include "stdarg.h"
#include "string.h"
#include
#define QHTTPPOST(x) "AT+QHTTPPOST="#x",10,10" //POST请求,参数为要发送的字符串长度
int main(void)
{
char data[]="123";
char len=0;
len = strlen(data);
printf("%s\r\n",QHTTPPOST(len));//输入长度,但是直接把len当成了字符串拼接了
return 0;
}
因为#define是在编译的时候已经确定了的,所以不可使用产量
我引用ChatGPT作答:在C语言中,使用宏定义连接符时,如果要拼接变量的值,需要使用另一个宏定义来将变量的值转换为字符串。这个宏定义是 #,称为字符串化运算符。
以下是修改后的代码:
#include "stdio.h"
#include "stdarg.h"
#include "string.h"
#include <unistd.h>
#define QHTTPPOST(x) "AT+QHTTPPOST=\"" #x "\",10,10" //POST请求,参数为要发送的字符串长度
int main(void) {
char data[] = "123";
char len = 0;
len = strlen(data);
printf("%s\r\n", QHTTPPOST(len)); //输出:AT+QHTTPPOST="3",10,10
return 0;
}
在宏定义中,#x将 x 参数转换为字符串,然后将其与其他字符串拼接起来。
注意到字符串化运算符 # 要放在字符串字面值的引号内部,而不是字符串字面值的外部。在宏定义中,整个字符串字面值用双引号括起来,因此我们需要在 #x 前后添加双引号。
这个功能估计不行,因为宏是在预编译的时候展开的,不是根据运行时候来动态决定的。
要这么搞直接用个字符串format就行了
#define QHTTPPOST(x) printf("AT+QHTTPPOST=%d,10,10",x)
#include "stdio.h"
#include "stdarg.h"
#include "string.h"
#include <unistd.h>
#define QHTTPPOST(x) printf("AT+QHTTPPOST=%d,10,10",x) //POST请求,参数为要发送的字符串长度
int main(void)
{
char data[]="123";
char len=0;
len = strlen(data);
printf("%s\r\n",QHTTPPOST(len));//输入长度,但是直接把len当成了字符串拼接了
return 0;
}
在宏定义中无法直接访问变量值,因为宏定义是在预处理阶段展开的,而变量是在编译阶段才有值。不过可以通过传递参数的方式,在宏定义中使用变量的值。
可以试试下面的方式:
#include "stdio.h"
#include "stdarg.h"
#include "string.h"
#include <unistd.h>
#define QHTTPPOST(x) printf("AT+QHTTPPOST=%d,10,10",(int)x); //POST请求,参数为要发送的字符串长度
int main(void)
{
char data[]="123";
char len=0;
len = strlen(data);
QHTTPPOST(len); //输入长度,但是直接把len当成了字符串拼接了
return 0;
}
以下答案由GPT-3.5大模型与博主波罗歌共同编写:
要将宏定义连接符和变量值拼接在一起,可以使用宏定义的字符串化和连接操作符。字符串化操作符#将变量或表达式转换为字符串,连接操作符##将两个符号连接成一个标识符。
你可以像下面这样修改你的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define QHTTPPOST(x) "AT+QHTTPPOST=" #x ",10,10"已黑化的小白
int main(void)
{
char data[] = "123";
char len = 0;
char cmd[32] = {0}; // 定义一个缓冲区用于拼接字符串
len = strlen(data);
sprintf(cmd, "%s", QHTTPPOST(len)); // 使用sprintf将字符串拼接到cmd缓冲区中
printf("%s\r\n", cmd); // 打印cmd缓冲区中的内容
return 0;
}
在宏定义中,我们使用#x将变量x转换成字符串,在主函数中,我们使用sprintf将字符串拼接到缓冲区中。最后,使用printf打印生成的命令字符串。
输出结果应为:
AT+QHTTPPOST=3,10,10
如果我的回答解决了您的问题,请采纳!
预处理的头文件展开很好理解,就是把头文件内容进行展开
看个例子 :
没有头文件时
#define MAX 20
int main()
{
int a = MAX;
++ return 0;
}
++
这个预处理后的.i文件内容很短。加上头文件后就变很长了
这就是把头文件展开了。
"AT+QHTTPPOST=##x,10,10"