如何修复无限运行的嵌套while循环?

时间:2012-10-21 21:58:28

标签: c++ infinite-loop

所以我遇到了另一个问题。我一直试图解决这个问题大约一个小时没有运气。我不能让这个嵌套while循环工作。代码应根据输入放入行,但目前它将永远存在。

#include <iostream>
using namespace std;
void PrintLines(char characterValue, int characterCount, int lineCount);

// I'm going to have to change char characterValue to int characterValue
// will this still work if they are in seperate files?

void PrintLines(char characterValue, int characterCount, int lineCount)
    {
        while (lineCount--)                 //This is the problem
        {
            while (characterCount--)
            {
                cout << characterValue;
            }
            cout << "\n";
        }


    }

int main()
{

    char Letter;
    int Times;
    int Lines;

    cout << "Enter a capital letter: ";
    cin >> Letter;
    cout << "\nEnter the number of times the letter should be repeated: ";
    cin >> Times;
    cout << "\nEnter the number of Lines: ";
    cin >> Lines;

    PrintLines(Letter, Times, Lines);



    return 0;

当我这样做时,检查它是否正常工作。我看到它确实......

        while (lineCount--)                 //This is to check
        cout << "\n%%%";
        {
            while (characterCount--)
            {
                cout << characterValue;
            }
        }

它打印:(如果Lines = 4,Times = 3,Letter = A)

%%%
%%%
%%%
%%%AAA

5 个答案:

答案 0 :(得分:2)

    while (lineCount--)                 //This is the problem
    {
        while (characterCount--)
        {
            cout << characterValue;
        }
        cout << "\n";
    }

在lineCount的第一次迭代之后,characterCount为负数。你继续递减它,它会永远不会再次达到零,直到它溢出。

执行:

    while (lineCount--)                 //This is the problem
    {
        int tmpCount = characterCount;
        while (tmpCount--)
        {
            cout << characterValue;
        }
        cout << "\n";
    }

答案 1 :(得分:2)

问题在于您似乎期望characterCount在循环的每次迭代中获得其原始值。但是,由于您在内部循环中更改它,它会转到-1,并且在您返回0之前需要一段时间。您需要保留原始characterCount,例如,使用专门针对每个循环的变量。

答案 2 :(得分:1)

而不是“%%%”,打印一些有用的内容,例如characterCountlineCount的值。然后你会看到你的循环正在做什么,最终,你做错了什么。

答案 3 :(得分:0)

这应该修复你的代码。你的characterCount减少到零以下,我阻止了这个:

void PrintLines(char characterValue, int characterCount, int lineCount)
{   
    while (lineCount--)                 
    {   
        int cCount = characterCount;//This was the problem

        while (cCount--) // and this fixes it
        {   
            cout << characterValue;
        }   

        cout << "\n";
        cCount = characterCount ; 
    }   

}

答案 4 :(得分:0)

除非你被限制使用嵌套循环,否则做这样的事情可能更简单:

// Beware: untested in the hopes that if you use it, you'll need to debug first
std::string line(Times, Letter);

std::fill_n(std::ostream_iterator<std::string>(std::cout, "\n"), 
            lineCount,
            line);
相关问题