将数字打印为字符串类型的数字

Print number as number in string type

本文关键字:数字 类型 字符串 打印      更新时间:2023-10-16

我有以下代码:

string a =  "wwwwaaadexxxxxx";

预期输出:"w4a3d1e1x6";

我的代码中有int count = 1; ... count++;

另外,在我的代码的某个地方,我必须将此计数打印为a[i],但仅作为数字…比如1、2、3,而不是1、2、3的等效字符。

我正在尝试以下内容:printf("%c%d",a[i],count);

我也读到像这样的东西:

stringstream ss;
ss << 100 

在CPP中正确的方法是什么?

编辑:

so i修改代码,在字符串的索引i处添加一个数字:

        stringstream newSS;
        newSS <<  count;
            char t = newSS.str().at(0);
            a[i]  = t;

您可以使用stringstream将字符串和计数连接起来,

stringstream newSS;
newSS << a[i] << count;

,然后最后将其转换为字符串,然后打印或返回(如果在函数中完成)

string output = newSS.str();
cout << output << endl;

但是如果您的目标只是打印输出,那么使用printf就可以了。

如果需要就地更新,则可以使用两个指针。让它们是i,j。
您使用j来设置新值,使用i来计算计数。这是标准的runLength编码问题

没有"正确"的方法。你可以使用snprintf, stringstream等。或者你可以滚动你的算法。假设这是一个以10为基数的数,您需要以10为基数的数。

#include <iostream>
#include <string>
#include <algorithm>
int main(void)
{
    int a = 1194;
    int rem = 0;
    std::string output;
    do {
        rem = a % 10;
        a = a / 10;
        output.append(1, rem + '0');
    } while(a != 0);
    std::reverse(output.begin(), output.end());
    std::cout << output << std::endl;
    return 0;
}