c - 试图找出如何在 c 中输出电话号码?

标签 c arrays

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

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 或其他数字类型的唯一原因是如果您必须对其进行算术运算 (除非家庭作业规范要求)。不要被电话号码由数字组成这一事实所迷惑 - 将其存储为字符串最有意义!

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

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

一旦有了它,就可以更轻松地控制它的打印方式:

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

关于c - 试图找出如何在 c 中输出电话号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54482474/

相关文章:

c - 将多维数组写入文本文件

javascript - 在表中显示数组中的日期

python - 如何在 python 中使用 Objectpath 导航包含数组的 JSON 文件以选择值?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c - 在 C 中处理 SIGTSTP 信号

c++ - 对于 CUDA 的嵌套循环

c - 堆排序适用于字符串,但不适用于整数

python - 循环以最小化python中数组的功能

arrays - 显示数组/列表的内容

c - 用 C 读取文本文件,跳过第一行