有什么方法可以使用for循环与字符串宏
Is there anyway to use for loop with string macro?
我有以下定义:
#define STRING_OBJECT_1 "bird"
#define STRING_OBJECT_2 "dog"
#define STRING_OBJECT_3 "cat"
#define STRING_OBJECT_4 "human"
#define STRING_OBJECT_5 "cow"
#define STRING_OBJECT_6 "snake"
#define STRING_OBJECT_7 "penguin"
#define STRING_OBJECT_8 "monkey"
我想只使用STRING_OBJECT_ + "(number string)"
来编号STRING_OBJECT
,所以基本上不直接键入STRING_OBJECT_1
。
在c++中是否有使用for循环的字符串宏?
在c++中是否有使用for循环的字符串宏?
不,没有。
在编译源代码以创建目标代码之前处理宏。 for
循环中变量的值是在运行时设置的。因此,它们不能使用宏。
最好的办法是在代码中增加一个数组变量,并在for
循环中使用该数组变量。
#define STRING_OBJECT_1 "bird"
...
#define STRING_OBJECT_8 "monkey"
std::string object_array[] = {STRING_OBJECT_1, ..., STRING_OBJECT_8};
for ( int i = 0; ... )
{
do_something(object_array[i]);
}
不,你不能这么做。不属于C/c++ 语言的宏。
宏被预处理器按编译时间替换。您无法在运行时更改宏。
相关文章:
- 在循环C++中指定字符串之后,不会打印该字符串
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- C++-字符串是否包含一个带有简单循环的单词
- 在 c++ 中查找字符串中没有循环的数字总和
- 比较两个字符串后卡在无限循环中
- C++ - 使用基于范围的 for 循环将字符值分配给向量中的字符串不会分配值
- 而循环跳过 cin.getline() 对于 C 字符串
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 如何使用将字符串拆分为 for 循环中的变量的程序
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- 循环访问还包含未使用元素的字符串数组
- 循环访问资源字符串表
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 修改向量中的字符串?(不使用循环)
- For 循环字符串忽略字符
- 如何按空格循环字符串?我怎么知道字符串中我当前所在的单词的索引号
- 在 c++ 中循环字符串读取器
- 如何在 c++ 中循环字符串
- 分段错误,通过std按字符循环字符串