我应该编写一个程序,在其中打印出短的(压缩的单词),长的。例如: 8S2Q3R 是 SSSSSSSSQQRRR 的缩写。现在,我编写了这个简短的程序,该程序不起作用(循环不断)。我很确定我不应该将 while循环放在 for循环中,但是我不确定如何确切地解决此问题。
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char word[80];
cin >> word;
int length = strlen(word);
int counter = 1;
for (int i = 0; i < length; i++) {{
while (word[i] == word[i + 1]) {
counter++;
}
cout << counter << word[i];
}
return 0;
}
类似地,如果我必须打印出一个长单词而一个短单词,那么我编写的程序也不起作用(输出是一堆象形文字):
#include <iostream>
#include <string.h>
using namespace std;
int number = 0;
bool Number(char c) {
switch(c) {
case '1':
number = 1;
return true;
break;
case '2':
number = 2;
return true;
break;
case '3':
number = 3;
return true;
break;
case '4':
number = 4;
return true;
break;
case '5':
number = 5;
return true;
break;
case '6':
number = 6;
return true;
break;
case '7':
number = 7;
return true;
break;
case '8':
number = 8;
return true;
break;
case '9':
number = 9;
return true;
break;
case '0':
number = 0;
return true;
break;
default:
return false;
}
}
int main()
{
char word[80];
cin >> word;
int length = strlen(word);
int counter = 1;
for (int i = 0; i < length; i++) {
if (Number(word[i])) {
for (int j = 0; j < number; i++) {
cout << word[i];
}
} else {
continue;
}
}
return 0;
}
答案 0 :(得分:0)
不确定这是否是您想要的,但我假设可以有2个或更多连续数字,并且数字后面只能有一个字符。
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int
main ()
{
char word[80];
char out[128];
char temp[10];
cin >> word;
int len = strlen (word);
int index = 0;
int numindex = 0;
int count;
while (index < len) {
while (word[index] >= '0' && word[index] <= '9') {
temp[numindex++] = word[index++];
}
temp[numindex] = 0;
count = atoi (temp);
numindex = 0;
char ch = word[index++];
for (int i = 0; i < count; i++) {
out[i] = ch;
}
out[count] = 0;
cout << out;
}
return 0;
}