c++ - 为什么 For 循环中的 While 循环在我的程序中不起作用?
问题描述
我应该制作一个程序,我应该打印出短的(压缩字),有长的。例如:8S2Q3R是SSSSSSSSQQRRR的缩写。现在,我做了这个小程序,它不起作用(无休止地循环)。我很确定我不应该将while-loop放在for-loop中,但我不确定如何解决这个问题。
#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;
}
解决方案
不确定这是否是您想要的,但我假设可以有 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;
}
推荐阅读
- excel - 重复转置公式的简单循环
- ios - 从通知中心删除“本地或远程通知”
- php - 有什么方法可以检查关系值是否存在然后返回数组,否则返回空白数组
- object - 如何在 ES6 中从子方法引用父对象?
- javascript - 在 Angular js 中显示错误消息的问题
- android - Android NDK获取二进制文件的md5
- oauth - 如何通过在 Alexa 开发者控制台中配置帐户链接部分来获取 lambda 函数中的 google oauth 刷新令牌?
- java - IText 7 如何在不重叠页面内容的情况下在标题中添加 Div 或段落?
- python - 从列表写入 csv 文件,10 x 10
- c# - 从不同的表和用户输入在 SQL 中插入值