试图弄清楚如何在c中输出电话号码? [英] Trying to figure out how to output a phone number in c?

查看:150
本文介绍了试图弄清楚如何在c中输出电话号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试输入电话号码并以(888)999-1111格式打印出来,但是当我尝试将其打印出来时,我得到了一些奇怪的输出,而这并不是我希望重新获得的输出.我正在输入中和打印功能bt中打印出电话的值,它们是不同的.输入功能中的一个是正确的,但在打印功能中它是不正确的.预先感谢您的帮助.

I am trying to input a phone number and print it out in this format (888)999-1111 format but when i am trying to print it out i get some weird output that is not what i am expecting to get back out. I am printing out the values of phone both in the input and in the print function bt they are different. The one in the input function is correct but it isnt correct in the print function. Thanks in advance for the help.

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;
}

推荐答案

将值存储为intlong int或其他数字类型的唯一原因是必须进行算术运算上的内容(除非家庭作业分配规范要求).电话号码是由数字组成的事实,不要被愚弄了-将其存储为字符串最有意义!

The only reason you'd need to store a value as an int, a long int, or another numeric type is if you had to do arithmetic on it (unless it's required by a homework assignment specification). Don't be fooled by the fact that a phone number is composed of numbers - it makes most sense to be stored as a string!

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

If you can store the phone number as a string, you should:

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

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

Once you have that, it's easier to perform string manipulation on it:

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

这篇关于试图弄清楚如何在c中输出电话号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆