1、转换字符串的输入格式为:原来字符串里的字符+该字符连续出现的个数,例如字符串:1233422222,转化为1121324125。
我们用sprintf来实现,类同printf。
#include "iostream" #include "string" using namespace std; int main() { cout << "Enter the numbers: " << endl; string str; cin >> str; size_t ilength = str.length(); int icount = 1; char cMyChar[50]; cMyChar[0] = '\0'; int k; for (k = 0; k < ilength - 1; k++) { if (str[k] == str[k + 1]) //预判断 { icount++; //记录字符个数 } else { sprintf(cMyChar + strlen(cMyChar), "%c%d", str[k], icount); icount = 1; } } if (str[k] == str[k - 1]) ; else icount = 1; sprintf(cMyChar + strlen(cMyChar), "%c%d", str[k], icount); cout << cMyChar << endl; return 1; }
2、整数转换成字符串
#include "iostream" using namespace std; int main() { int iMyData; cin >> iMyData; char cToTransfer[56]; char cTemp[56]; int icount = 0; //标记位数 while(iMyData) { cTemp[icount++] = iMyData % 10 + '0'; iMyData = iMyData / 10; } cTemp[icount] = '\0'; cout << cTemp << endl; icount--; int j = icount, i = 0; while(j >=0) { cToTransfer[i++] = cTemp[j--]; } cToTransfer[i] = 0; cout << cToTransfer << endl; return 1; }
3、字符串转换成整数
#include "iostream" using namespace std; int main() { char iMyData[56]; cin >> iMyData; int iToTransfer[56]; int cTemp[56]; int icount = 0; //标记位数 int iSum = 0; while(iMyData[icount]) { iSum = iSum * 10 + iMyData[icount] - '0'; icount++; } cout << iSum << endl; return 1; }