【发布时间】:2021-12-23 12:33:49
【问题描述】:
#include<stdio.h>
#include <string.h>
#define STR1 "F:\\c\\projects\\Banking Management System\\data\\"
#define STR2 "pwd.txt"
#define STR3 STR1 STR2
#define PPCAT_NX(A, B) A##B
#define PPCAT(A, B) PPCAT_NX(A, B)
void main() {
printf("\n%s", STR3);
printf("\n%s ",PPCAT(STR1, STR2));
}
问题说明
第一个 ("printf("\n%s", STR3);") 工作正常,给我所需的输出如下:
F:\c\projects\Banking Management System\data\pwd.txt
但是,第二个 (printf("\n%s ",PPCAT(STR1, STR2));" 给了我以下错误:
|=== 构建文件:“无项目”中的“无目标”(编译器:未知)===| F:\c\projects\Banking Management System\src\stringConcatMacro.c||在函数'main'中:| F:\c\projects\Banking Management System\src\stringConcatMacro.c|4|error: pasteing ""F:\c\projects\Banking Management System\data\"" and ""pwd.txt"" 不给一个有效的预处理令牌| F:\c\projects\Banking Management System\src\stringConcatMacro.c|9|注:在宏'PPCAT_NX'的定义中| F:\c\projects\Banking Management System\src\stringConcatMacro.c|15|注:在宏'PPCAT'的扩展中| F:\c\projects\Banking Management System\src\stringConcatMacro.c|15|注:在宏'STR1'的扩展中| ||=== 构建失败:1 个错误,0 个警告(0 分钟,0 秒)===|
我想使用第二种方法,其中我可以通过我的路径 (STR1) 传递不同的文件名(而不是使用固定的 STR2)。
第二个选项哪里出了问题? enter code here
任何帮助将不胜感激。
【问题讨论】:
-
只是
printf("%s", STR1 STR2);。不,你不能##两个"strings",这是不可能的.. -
@KamilCuk - 谢谢。有没有办法让用户在以下宏中输入 STR2?:#define STR3 STR1 STR2
-
那么
#define STRCONCAT(a, b) a b?这样的宏有什么价值吗?只需写a b。 -
请记住,字符串文字连接仅适用于文字。如果要在运行时提供文件名,那么您也必须在运行时使用
strncat等进行连接。 -
@KamilCuk - #define STRCONCAT(a, b) a b 非常适合我。这就是我要找的东西?我不想使用 strcat()、snprintf() 等将路径和文件名存储在变量中。谢谢您的帮助。
标签: c gcc codeblocks preprocessor-directive