c - 试图弄清楚如何在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;
}
解决方案
您需要将值存储为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);
推荐阅读
- python - 如何检查变量是否不等于字符串
- mysql - MySQL LOCATE 与 Bigquery 的等价物是什么?
- python - Enhanced-dpy discord bot 在本地运行良好,但在 Heroku 中出现错误
- sql-server - SqlReader 读取时存储过程结果集存储在哪里?
- asp.net-core - 让 .NET 5 Web API 在 IIS 中一直运行
- r - 基于R中的其他数据集向一个数据集添加一行
- php - PHP“while”循环没有为每个循环执行第二个命令
- interrupt - 在 ISR 执行期间禁止在 esp32 上加载
- excel - 尝试从本地 Excel 表访问谷歌表单 gsheet 中的数据
- c++ - C++ 栈实现,检查括号的正确性