为什么 For 循环中的 While 循环在我的程序中不起作用?

Why doesn't a While Loop inside a For Loop work in my program?

本文关键字:循环 程序 不起作用 我的 While For 为什么      更新时间:2023-10-16

我应该制作一个程序,我应该在其中打印出短的(压缩单词),长一个。例如: 8S2Q3R 对于 ssssssssssqrrr 而言是短的。现在,我制作了这个简短的程序,该程序不起作用(无休止地循环)。我敢肯定,我不应该在 for-for-for-for-for-for-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;
}