gpt4 book ai didi

c++ - 测试位以创建字符串 - 有更好的方法吗?

转载 作者:太空狗 更新时间:2023-10-29 23:38:30 24 4
gpt4 key购买 nike

此代码有效,但我想知道是否有更好的方法。基本上我需要测试位,并根据位的状态将适当的一个或多个字符写入字符串。存在空格是因为字符将以固定宽度的字体显示,我想防止它们四处移动。 C 或 C++ 都可以。

const char* Letters[10] = {"A", "B", "Sl", "St", "R", "L", "U", "D", "RS", "LS"};
const char* Ext[2] = {"X", "Y"};
const char* Spaces[10] = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "};

char str[60];
char FinalString[60];

void MakeBitString(u16 data, u16 dataExt) {

int x;
strcpy(str, "");

for (x = 0; x < 2; x++) {

//X and Y
if(dataExt & (1 << x)) {
strcat(str, Spaces[x]);
}
else
strcat(str, Ext[x]);
}

for (x = 0; x < 10; x++) {

//the rest
if(data & (1 << x)) {
strcat(str, Spaces[x]);
}
else
strcat(str, Letters[x]);
}

strcpy(FinalString, str);
}

最佳答案

  • 使用 std::string 代替 char* 和 strcat;
  • 为什么需要带空格的数组?似乎只有一个空格;
  • 两个 u16 参数的代码几乎相同 - 编写一个小函数并调用它两次;
  • 不要将结果写入全局变量 - 返回 std::string

关于c++ - 测试位以创建字符串 - 有更好的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/706477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com