c - 'for'块内的字符串“连接”
问题描述
我正在尝试在 C 中实现某种“连接”以在一个字符串中使用几个值。
代码如下所示:
#include <stdio.h>
#define A "A"
int main() {
char *textArray[] = {"a", "b", "c"};
int intArray[] = {1, 2, 3};
int n;
// count intArray[] lengh
// example taken from the https://www.sanfoundry.com/c-program-number-elements-array/
n = sizeof(intArray)/sizeof(int);
int i;
char *concat;
for (i=0; i<n; i++) {
// check if values are accessible
printf("TEST: Macro: %s, textArray's value: %s, intArray's value: %d\n", A, textArray[i], intArray[i]);
// making concatenation here - this will work
concat = "Macro: " A " textArray's value: '' intArray's value: ''";
// this will NOT work
// expected result == 'Macro: A textArray's value: a intArray's value: 1' etc
// concat = "Macro: " A " textArray's value: " textArray[i] " intArray's value: " intArray[i];
printf("%s\n", concat);
}
return 0;
}
此代码A
仅在使用宏的值时工作正常:
$ ./array_test TEST: Macro: A, textArray's value: a, intArray's value: 1 Macro: A textArray's value: '' intArray's value: '' TEST: Macro: A, textArray's value: b, intArray's value: 2 Macro: A textArray's value: '' intArray's value: '' TEST: Macro: A, textArray's value: c, intArray's value: 3 Macro: A textArray's value: '' intArray's value: ''
但是,如果我尝试使用textArray[i]
,即:
...
// making concatenation here - this will work
// concat = "Macro: " A " textArray's value: '' intArray's value: ''";
// this will NOT work
// expected result == 'Macro: A textArray's value: a intArray's value: 1' etc
concat = "Macro: " A " textArray's value: " textArray[i] " intArray's value: " intArray[i];
printf("%s\n", concat);
...
我在编译时出错:
$ gcc array_test.c -o array_test array_test.c: In function ‘main’: array_test.c:26:53: error: expected ‘;’ before ‘textArray’ concat = "Macro: " A " textArray's value: " textArray[i] " intArray's value: " intArray[i];
所以问题是:我在这里做错了什么,实现目标的正确方法是什么?
UPD:最终目标是将一个字符串传递给类似的函数mysql_query()
,例如mysql_query(conn, concat)
其中concat
将包含类似的值"INSERT INTO TableName VALUES('textValue', 'intValue')"
。
解决方案
"string" "string1" "string2"不是串联。它只是字符串文字的语法正确形式之一。
推荐阅读
- java - 使用 Mockito,如何匹配列表中地图的键值对?
- c++ - 如何迭代具有相同基类的元素元组
- python - 将while循环更改为for循环以查找两个生日相同的人
- angular - 错误:尝试区分“”时出错。只允许使用数组和可迭代对象
- rest - HTTP 响应编码问题
- python - 找不到页面 (404) 没有购物车与给定的查询匹配
- kotlin - 如何正确地向 PublishSubject 施加背压?
- amazon-web-services - 如何在 react-native typescript 模板中配置 Amplify UI 组件
- shell - 编写一个 shell 脚本来查找文件中存在的所有元音并打印相应的单词
- python - python程序打印一个变量然后说它没有定义。为什么?