首页 > 解决方案 > 试图弄清楚如何在c中输出电话号码?

问题描述

我正在尝试输入电话号码并以这种格式 (888)999-1111 格式打印出来,但是当我尝试打印出来时,我得到了一些奇怪的输出,这不是我所期望的。我在输入和打印功能中都打印出电话的值,它们是不同的。输入功能中的那个是正确的,但在打印功能中是不正确的。在此先感谢您的帮助。

int phoneInput(void)
{
    long int phone = 0;

    printf("Input the politicians phone number with no speaces: ");
    scanf("%ld", &phone);
    printf("test : %ld", phone);
return phone;
}

int printPhone(long int phone)
{
    int i = 10; //the number of digits in the phone
    char output[11];

    printf("Test: %ld", phone);

    for (i = 0; i < 10; i ++)
    {
    while (phone > 0)
    {
            output[i] = phone % 10;
            phone /= 10;
    }
    }

    printf("- Phone number: (");
    i = 0;
    for (i = 0; i < 3; i++)
    {
            printf("%d", output[i]);
    }

    printf(")");
    i = 3;
    for(i = 3; i < 6; i++)
    {
            printf("%d", output[i]);
    }
    i = 6;
    printf("-");
    for(i = 6; i < 10; i++)
    {
            printf("%d", output[i]);
    }

return 0;
}

标签: carrays

解决方案


您需要将值存储为int、 along int或其他数字类型的唯一原因是您必须对其进行算术运算(除非作业分配规范要求)。不要被电话号码由数字组成的事实所迷惑 - 将其存储为字符串是最有意义的!

如果您可以将电话号码存储为字符串,您应该:

char *phoneInput(void)
{
    static char phone[100];
    printf("Input the politicians phone number with no speaces: ");
    fgets(phone, 100, stdin);
    return phone;
}

一旦你有了它,就更容易对其执行字符串操作:

printf("(%.3s)%.3s-%.4s\n", phone, phone + 3, phone + 6);

推荐阅读