读数字并转换为单词

时间:2017-01-26 01:20:12

标签: c++ c++11

我是c ++的新手,我必须编写一个程序,用一个用户的4位数字并将其转换为单词,即7238将被写为7二三八。然而它写的每个数字都是未知的。任何关于菜鸟的建议都将不胜感激。

#include iostream

using namespace std;

int main() {


     char number;


    cout << "Please enter a 4 digit number: ";

     cin >> number;

        switch(number){

        case 1 :
            cout<< "one"; 
            break;
        case 2 :
            cout<< "two";
            break;
        case 3 :
            cout<< "three";
            break;
        case 4 :
            cout<< "four";
            break;
        case 5 :
            cout<< "five";
            break;
        case 6 :
            cout<< "six";
            break;
        case 7 :
            cout<< "seven";
            break;
        case 8 :
            cout<< "eight";
            break;
        case 9 :
            cout<< "nine";
            break;
        case 0 :
            cout<< "zero";
            break;

        default :
            cout << "UNKNOWN.";
   }

}

4 个答案:

答案 0 :(得分:1)

听起来像是家庭作业,但这里有一些提示。将setuid变量更改为number类型您可以使用除法和模数将数字分解为单个变量。我会把它们填入一个整数数组。

int

然后在switch语句周围使用一个循环,其中你的计数器小于4(数组的长度)。确保在每个循环结束时增加计数器。哦,它是int array[4]; arr[0] = (number / 1000) % 10; // Thousands ....... // You do the hundreds and tens arr[3] = (number % 10); // Ones

答案 1 :(得分:1)

to_stringrange based for

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int number;
    cout << "Enter the number: ";
    cin >> number;

    string strnum = to_string(number);
    for (auto c : strnum)
    {
        switch (c)
        {
            case '0': cout << "zero "; break;
            case '1': cout << "one "; break;
            case '2': cout << "two "; break;
            case '3': cout << "three "; break;
            case '4': cout << "four "; break;
            case '5': cout << "five "; break;
            case '6': cout << "six "; break;
            case '7': cout << "seven "; break;
            case '8': cout << "eight "; break;
            case '9': cout << "nine "; break;
            default: cout << "non-digit"; break;
        }
    }
    return 0;
}

答案 2 :(得分:0)

您需要在case语句中添加ascii值。目前,您正在比较数字的ascii值和数字0 - 9。 可以在此处找到值:http://www.asciitable.com/

答案 3 :(得分:0)

您的变量属于char类型。 char存储一个字符,通常是ASCII编码的。例如,如果用户输入“1”,通常会转换为49的整数值,而不是1.读入int或更改案例标签以使用字符文字:

case '1':
    cout << "one";
    break;

然后您可以使用循环读取多个数字。