我正在尝试输入一个电话号码并以这种格式 (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;
}
最佳答案
您需要将值存储为 int
、long 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/