C 中将字符串与 int 连接

标签 c string int strcat

#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/

相关文章:

php - 防止 PHP 解释源代码中字符串中的新行

c++ - 模块化功能背后的逻辑

swift - CGRect 选项之间有什么区别?

c++ - 无限循环的 while 循环内的 switch 语句

python - 了解 pandas 系列提取函数中的正则表达式

c - 构造 GTK 组合框时从不兼容的指针类型初始化

C LINUX\WINSOCK-检查Send中的FIN包

c - 如何将二维数组的一部分复制到一维数组中?

javascript - 在 JavaScript 中将字符串转换为 HTML

c - 删除二叉树中仅通过引用传递节点的节点