3-2 WERTYU(WERTYU,UVa10082)

3-2 WERTYU(WERTYU,UVa10082)


把手放在键盘上时,稍不注意就会往右错一位。这样,输入Q会变成输入W,输入J会变成输入K等。键盘如图3-2所示。

输入一个错位后敲出的字符串(所有字母均大写),输出打字员本来想打出的句子。输入保证合法,即一定是错位之后的字符串。例如输入中不会出现大写字母A。

样例输入:

O S, GOMR YPFSU/

样例输出:

I AM FINE TODAY.

【分析】

和例题3-1一样,每输入一个字符,都可以直接输出一个字符,因此getchar是输入的理想方法。问题在于:如何进行这样输入输出变换呢?一种方法是使用if语句或者switch语句,如"if(c == 'W') putchar('Q')"。但很明显,这样做太麻烦。一个较好的方法是使用常量数组,下面是完整程序:

#include<stdio.h>
char s[] = "`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./";
int main() {
	int i, c;
	while((c = getchar()) != EOF) {
		for (i=1; s[i] && s[i]!=c; i++); //找错位之后的字符在常量表中的位置
		if (s[i]) putchar(s[i-1]); //如果找到,则输出它的前一个字符
		else putchar(c);
	}
	return 0;
}

原文如下:

A common typing error is to place the hands on the keyboard one rowto the right of the correct position. So ‘Q’ is typed as ‘W’ and ‘J’ is typedas ‘K’ and so on. You are to decode a message typed in this manner.

Input

Input consists of several lines of text. Each line may containdigits, spaces, upper case letters (except Q, A, Z), or punctuation shown above[except back-quote (‘)]. Keys labelled with words [Tab, BackSp, Control, etc.]are not represented in the input.

Output

You are to replace each letter or punction symbol by the oneimmediately to its left on the ‘QWERTY’ keyboard shown above. Spaces in theinput should be echoed in the output.

Sample Input

O S, GOMR YPFSU/

Sample Output

I AM FINE TODAY.

提示3-19:善用常量数组往往能简化代码。定义常量数组时无须指明大小,编译器会计算。

C++源码,用strchar()函数实现,自己最好写一下,再看。

#include <iostream>

#include <cstdio>

#include <cstring>

#include <algorithm>

using namespace std;

char s[] ="`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./";

int main(void)

{

    char c;

    while ((c = getchar()) !=EOF) {

        char *p = strchr(s,c);

        if (!p) putchar(c);

        elseputchar(s[p-s-1]);

    }

    return 0;

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追梦2017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值