Search code examples
c++digits

C++ convert digits to words


I think my logic is correct but the while loops infinitely, outputting zero. Here is my code:

int currentMSD, currentNum = num;
if (currentNum >= 0 && currentNum < 100) {
    currentMSD = 10;
} else if (currentNum >= 100 && currentNum < 1000) {
    b1 = b * msd;
    b2 = num3 - b1;
    num3 = b2;
    switch(b) {
        case 1:
            cout << "one ";
            break;
        case 2:
            cout << "two ";
            cout << "five ";
            break;
        case 6:
            cout << "six ";
            break;
        case 9:
            cout << "nine ";
            break;
        case 0:
            cout << "zero ";
          break;
        }
    }
    cout << '\n';
}

Solution

  • getMSD() function is faulty. replace it with this new one

    int getMSD(int num) {
    
    int currentMSD = 1, currentNum = num;
    
    if (currentNum >= 10 && currentNum < 100)
    {
        currentMSD = 10;
    }
    else if (currentNum >= 100 && currentNum < 1000)
    {
        currentMSD = 100;
    }
    else if (currentNum >= 1000 && currentNum < 10000)
    {
        currentMSD = 1000;
    }
    return currentMSD;
    }