免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1947 | 回复: 3
打印 上一主题 下一主题

[C] 请大家帮忙解答一道C语言习题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-07-17 10:14 |只看该作者 |倒序浏览
本帖最后由 green0sky 于 2013-07-17 11:02 编辑

编写程序可以把字母格式的电话号码翻译成数值格式:
Enter phone number: CALLATT
字母在键盘上的对应关系: 2=ABC 3=DEF 4=GHI 5=JKL 6=MNO, 7=PRS, 8=TUV, 9=WXY

(原电话号码中的非字母字符(数字或标点符号)保持不变。Enter phone number: 1-800-COL-LECT
这个要怎么编写才能同时输出数字和字母?

#include <stdio.h>

int main()

{
         char ch;
         printf("Enter phone number: ");
         while ((ch = getchar()) != '\n') {
         if(ch <= 'C')
                 printf("2");
         else if (ch <= 'F')
                 printf("3");
         else if (ch <= 'I')
                 printf("4");
         else if (ch <= 'L')
                 printf("5");
         else if (ch <= 'O')
                 printf("6");
         else if (ch <= 'S')
                 printf("7");
         else if (ch <= 'V')
                 printf("8");
         else if (ch <= 'Y')
                                                              
}

         printf("\n");

         return 0;
}

这个要怎么改才能同时输出数字和字母?

论坛徽章:
2
程序设计版块每日发帖之星
日期:2015-06-17 22:20:00每日论坛发贴之星
日期:2015-06-17 22:20:00
2 [报告]
发表于 2013-07-17 12:32 |只看该作者
提示: 作者被禁止或删除 内容自动屏蔽

论坛徽章:
2
2015年辞旧岁徽章
日期:2015-03-03 16:54:152015年迎新春徽章
日期:2015-03-04 09:56:11
3 [报告]
发表于 2013-07-17 16:45 |只看该作者
  1. /* digital pad */

  2. #include <ctype.h>
  3. #include <stdio.h>
  4. #include <string.h>

  5. #define ALEN(a) (sizeof(a)/sizeof((a)[0]))

  6. struct digital_map
  7. {
  8.         char digit;
  9.         const char *text;
  10. };

  11. static struct digital_map map_table[] =
  12. {
  13.         {'2', "ABC"},
  14.         {'3', "DEF"},
  15.         {'4', "GHI"},
  16.         {'5', "JKL"},
  17.         {'6', "MNO"},
  18.         {'7', "PRS"},
  19.         {'8', "TUV"},
  20.         {'9', "WXY"},
  21. };

  22. int char_to_digit(char c)
  23. {
  24.         int i;

  25.         for (i = 0; i < ALEN(map_table); ++i) {
  26.                 if (strchr(map_table[i].text, c) != NULL) {
  27.                         return map_table[i].digit;
  28.                 }
  29.         }
  30.         return c;
  31. }

  32. int main(void)
  33. {
  34.         char ch;

  35.         printf("Enter phone number: ");
  36.         while ((ch = getchar()) != '\n') {
  37.                 putchar(char_to_digit(toupper(ch)));
  38.         }
  39.         putchar('\n');
  40.         return 0;
  41. }
复制代码

论坛徽章:
0
4 [报告]
发表于 2013-07-17 21:05 |只看该作者
多谢热心回答,我刚入门,这个有点复杂,我还看不太懂。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP