gpt4 book ai didi

C 中将字符串与 int 连接

转载 作者:行者123 更新时间:2023-11-30 17:07:27 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <string.h>
int main(void)
{
//declaring variables
int num[10], action;
char longText[80], shortText[80] = { 0 };

//Program's Main menu
printf("You can use the following options:\nPlease select your desired action.\n");
scanf("%d", &action);
switch (action) //All of the possible options for the user
{
case 1:
{
switchIf(num);
break;
}
case 2:
{
newNumbers(num);
break;
}
case 3:
{
longToShortText(longText, shortText);
break;
}
}
}
void longToShortText(char longText[], char shortText[])
{
int i, j = 0, counter = 1, size;
printf("Please enter a series of letters.\n");
scanf("%s", longText);
size = strlen(longText);
for (i = 0; i < size; ++i)
{
if (longText[i] == longText[i + 1])
++counter;
else
{
shortText[j] = longText[i];
strcat(shortText[j], counter); // i know this is wrong, but i couldn't make it work with another string either.
printf("%c", shortText[j]);
counter = 1;
++j;
}
}

}这是我的一段代码,该函数正在获取一组字符(即:aaabbbccc),并且它应该计算每个字符被输入的次数,然后将字母发送到另一个字符串,然后我想连接计数器的value 到shortText[j],然后程序崩溃。 (错误列表中给出的错误是“'strcat':形式参数和实际参数1/2的类型不同”有什么方法可以让它发挥作用?

最佳答案

两种可能的方式。对于案例“aaabb”:

如果你想要“a3b2”:

shortText[j] = longText[i];
++j;
char aux[20];
sprintf(aux, "%d", counter);
printf("aux: %s, j: %d\n", aux, j);
strcat(shortText+j, aux);
counter = 1;
j += strlen(aux);

如果您想要“a\0\0\0\3b\0\0\0\2”(示例假设 4 个字节 int)

shortText[j] = longText[i];
++j;
memcpy(shortText+j, &counter, sizeof(counter));
printf("%c, %d, %d, %d\n", shortText[j-1], counter, sizeof(counter), j);
counter = 1;
j += sizeof(counter);

请注意第二种情况,因为您将无法再使用字符串函数(例如 strcatstrcpy ...)

关于C 中将字符串与 int 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34065939/

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