UVa 213 Message Coding

写一个解码程序,首先输入一个编码头,然后是一个编码序列,将这个编码序列进行解码;

1、discuss中的一个输入测试集迷惑了,每一个编码序列中,对每一个长度一定会有一个全1串结束,即使是最后一个译码字符,也会有全1串;

2、getline和cin对缓冲区的处理方式不同,混合使用时一定要注意;

3、将操作尽量函数化。


#include<iostream>
#include<iomanip>
#include<string>
#include<vector>
#include<cmath>

using namespace std;
 struct Pair {
	string s;
	char c;
};

//i is size of string, divided is No. value
string ItoString(int i, int divided) {
	string temp(i, '0');

	while (divided > 0) {
		if (divided % 2)
			temp[--i] = '1';
		else
			temp[--i] = '0';
		divided /= 2;
	}
	return temp;
}
char readchar()
{
	char ch;
	while (1) {
		ch = getchar();
		if (ch != '\r' && ch != '\n')
			return ch;
	}
}
int getlen(int c)
{
	int len = 0;
	while (c--)
		len = len * 2 + readchar() - '0';
	return len;
}
string readString(int c)
{
	string s = "";
	while (c--)
		s += readchar();
	return s;
}
int main()
{

#ifndef UVa
	FILE *fp;
	freopen_s(&fp, "data.in.txt", "r", stdin);
//	freopen_s(&fp, "data.out.txt", "w", stdout);
#endif
	string header;
	vector<Pair> pvec;
	
	for (int i = 1; i < 8; ++i)
		for (int j = 0; j < (pow(2,i) - 1); ++j) {
			Pair p;
			p.s = ItoString(i, j);
			p.c = 'a';
			pvec.push_back(p);
		}

	while(getline(cin,header)){
		for (int i = 0; i < header.size(); ++i)
			pvec[i].c = header[i];

		for (;;) {// each three bit
			int len = getlen(3);
			if (len == 0) 
				break;
			
			for (;;) {//each char
				string s = readString(len);
				bool allOne = true;
				for (string::iterator iter = s.begin(); iter != s.end(); ++iter)
					if (*iter != '1') {
						allOne = false;
						break;
					}
				if (allOne)
					break; 
				for (vector<Pair>::iterator iter = pvec.begin(); iter != pvec.end(); ++iter)
					if (iter->s == s) {
				      cout << iter->c;
					  break;
			        }
			}//endfor
			
		}//endfor
		
		cout << endl;
		string s2;
		getline(cin, s2);
	}//endwhile

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值