gpt4 book ai didi

c++ - 在数组 C++ 中插入整数

转载 作者:行者123 更新时间:2023-11-28 06:46:39 24 4
gpt4 key购买 nike

我编写了以下代码将类型为“aaadddbbbccc”的字符串转换为“a3d3b3c3”:

#include <iostream>
#include <string.h>
using namespace std;

void stringCompression(char *str,char *newStr){
int a[256] = {0};
int newCount = 0;
for(int i = 0; i < strlen(str) ; i++){
int j = str[i];
if (a[j] == 0 && strlen(newStr) <= strlen(str)){
a[j] = 1 ;
newStr[newCount] = str[i];
newCount++;
int count = 0;
for (int n = i; n < strlen(str); n++){
if(str[i] == str[n]){
count = count + 1;
}
}
newStr[newCount] =(char) count;
newCount++ ;
} else if (strlen(newStr) > strlen(str)){
strcpy(newStr,str);
}
}
}

int main() {
char str[] = "abcdabcdabcd";
char *newStr = new char[strlen(str)+1];
stringCompression(str,newStr);
cout << newStr;
return 0;
}

我的问题在步骤

newStr[newCount] =(char) count;

即使它被插入但输出不是a3b3c3d3而是a*squarebox*b*squarebox*c*squarebox*d*squarebox*。 squarebox 是 2*2 矩阵,其中一个值是所需的数字。我正在使用 Eclipse IDE。.我将衷心感谢您的帮助。我该如何纠正这个问题。我使用的方法是否正确?

提前致谢。

最佳答案

问题是

newStr[newCount] =(char) count;

根据ascii表(http://www.asciitable.com/)将数字“count”转换为该数字对应的字符,即“3”的“文本结尾”,不对应任何数字。

您应该将“count”转换为字符串。看这里例如: Easiest way to convert int to string in C++

但是,请注意它可能比一位数字长,例如,如果 count 是“11”,它将以字符串表示形式占用两个字母。

关于c++ - 在数组 C++ 中插入整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24880353/

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