0

所以我遇到了另一个问题。我一直试图解决这个问题大约一个小时,但没有运气。我无法让这个嵌套的 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 and Times = 3 and Letter = A)

%%%
%%%
%%%
%%%AAA
4

5 回答 5

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";
    }
于 2012-10-21T22:03:37.040 回答
2

问题是您似乎期望characterCount循环的每次迭代都会获得其原始值。但是,由于您在内部循环中更改它,它会到达-1并且需要很长时间才能回到0. 您需要保留原件characterCount,例如,使用专门为每个循环使用的变量。

于 2012-10-21T22:04:02.070 回答
1

代替“%%%”,打印一些有用的东西,比如characterCountand的值lineCount。然后你会看到你的循环在做什么,最终你做错了什么。

于 2012-10-21T22:00:12.723 回答
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 ; 
    }   

}  
于 2012-10-21T22:04:00.290 回答
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);
于 2012-10-21T22:22:59.877 回答