首页 > 解决方案 > 为什么 For 循环中的 While 循环在我的程序中不起作用?

问题描述

我应该制作一个程序,我应该打印出短的(压缩字),有长的。例如:8S2Q3RSSSSSSSSQQRRR的缩写。现在,我做了这个小程序,它不起作用(无休止地循环)。我很确定我不应该将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;
}

标签: c++for-loopwhile-loop

解决方案


不确定这是否是您想要的,但我假设可以有 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;
}

推荐阅读