现在的位置: 首页 > 综合 > 正文

电话号码翻译(华为上机试题8_31_3)

2018年03月16日 ⁄ 综合 ⁄ 共 1741字 ⁄ 字号 评论关闭

下面的代码借鉴了华为上机试题中所给出原代码的一点思路:

在贴代码前先看下这段不完善的代码:

..........

int i = 0;

char temp[100];

char ch;

while(ch != '\n')
{

scanf("%s%c",temp,&ch);
i++;
}

当从键盘输入one two three['  five按下回车键后,通过调试(黑体字为断点)可以发现

i = 0  ;temp = one,ch = ' '

i = 1  ;temp = two, ch = ' '

i = 2  ;temp = three['  , ch = ' ' 

i = 3  ;temp = five, ch = ' \n'

这样输入的目地就是为了顺利的取出空格作为分隔符所产生的字符串。

注意:scanf("%s%c",temp,&ch)与scanf("%s,%c",temp,&ch)的区别。

...........

/*

 * Author :zhuang_569 
 * Time : 2014/9/9  
 * description : 翻译电话号码
 * 题目:
 *  将电话号码one two ...nine zero翻译成1 2 9 0
 *  例如输入:one two three 输出:123
 *  输入:one two double Two 输出:1222
 *  输入:1 two 2 输出:ERROR
 *  输入:double double two 输出:ERROR
*/

#include "iostream"
#include "string"
using namespace std;

typedef  unsigned short int  INT16U;
/**************函数声明*******************/
void handle(void);

/**************全局变量声明*******************/
const char code[11][7] = {"zero","one","two","three","four","five","six","seven","eight","nine","double"};

char temp[100];
char end_sign= ' ';
int main(void)
{
handle();

return 0;
}

void handle(void)
{

int i = 0;
int double_flag = 0;
//double符号的标志位

//当出现两个double当出错处理
int back_up_val = 255;

int index = 0;
//统计输入的待翻译的电话号码的数量

int decode[100];
//存放翻译后的电话号码
int num = 0;
//翻译后的电话号码数量 

int match_flag = 0;
//输入的待翻译的电话号码是否正确标志位

cout<<"请输入待翻译的电话号码:";
while(end_sign!= '\n')
{

//输入一串字符用空分割可以得到被分割的字符
//输入一串字符one two three.temp可以分别等于one two three 
scanf("%s%c",&temp,&end_sign);
index++;

for(i=0; i<11;i++)
{

if((strcmp(temp,code[i])==0))
{
match_flag = 1;
//输入匹配

if(i < 10)
{
if(double_flag == 1)
{
double_flag = 0;

decode[num++] = i;
decode[num++] = i;
}
else
{
decode[num++] = i;
}
}
else if(i == 10)
{
double_flag = 1;
if((index-back_up_val) == 1)
{
cout<<"ERROR";
return;
}

back_up_val = index;
}

break;
//匹配后就跳出循环,节约时间
}
}

if(match_flag == 1)
{
match_flag = 0;
}
else
{
cout<<"ERROR";
return;
}
}

if(double_flag == 1)
//输入最后带翻译的电话号码为double
{
cout<<"ERROR";
return;
}

cout<<"翻译后的电话号码是:";
//输出译码后的电话号码
for(i=0; i<num; i++)
{
cout<<decode[i];
}

cout<<endl;
}

测试结果:

抱歉!评论已关闭.