none
Can anyone see why my program won't loop? RRS feed

  • Question

  • #include "stdafx.h"
    #include <iostream>

    using namespace std;

    int main()
    {
    char letter, nextnumber;
    int digit, num, counter;

    do
    {
    cout << "Program to convert telephone numbers expressed in letters into digits." << endl;
    cout << "Enter a phone number expressed in letters: ";
    cin >> letter;
    cout << endl;

    counter = 0;
    nextnumber = 0;

    while (counter < 7)// I think this loop is the problem.
    {
    if (counter == 3)
    cout << "-";

    if (65 <= letter && letter < 91)
    {
    num = static_cast<int>(letter)
    - static_cast<int>('A');

    digit = (num / 3) + 2;

    if (((num / 3 == 6) || (num / 3 == 7))
    && (num % 3 == 0))
    digit = digit - 1;

    if (digit > 9)
    digit = 9;

    cout << digit;
    }
    else if (97 <= letter && letter < 123)
    {
    num = static_cast<int>(letter)
    - static_cast<int>('a');

    digit = (num / 3) + 2;

    if (((num / 3 == 6) || (num / 3 == 7))
    && (num % 3 == 0))
    digit = digit - 1;

    if (digit > 9)
    digit = 9;
    cout << digit;
    }
    else
    cout << "Invalid input." << endl;

    cin >> letter;

    counter++;
    }

    cout << "Enter another number? (Y/N) ";// Why doesn't this execute after the number is displayed?
    cin >> nextnumber;
    } while (nextnumber == 'Y' || nextnumber == 'y');

    system("pause");
    return 0;
    }
    • Edited by Matt_Hardesty Friday, October 30, 2015 6:33 PM updated code
    Friday, October 30, 2015 8:57 AM

Answers

  • The problem is difficult to spot from a simple superficial examination of the code. One of the causes is that your message is shown completely "flat" in the forum, so that the alignment of the braces is not easy to see. I suggest using an editor that indents the code to align its blocks. In ths way you can spot problems such as the loop having a scope which is not what you thought. If this doesn't make the problem obvious, then you should use a debugger. Use the debugger to execute the code line by line, while watching the values of the variables, until you find the location where it doesn't behave as expected.
    Saturday, October 31, 2015 11:31 AM