C++常用程序
C++的示例程序:
1.
#if 0
/*1. C++中整数/浮点等转化为字符串
*/
#include <ostream> // for the << operator
#include <sstream> // for ostringstream
#include <string> // for string
template<class T>
std::string to_string(T const& obj)
{
std::ostringstream out;
out << obj;
return out.str();
}
#endif
#if 0
/*
* 2. 从字符串得到整数/浮点数
* */
#include <istream> // for the >> operator
#include <sstream> // for ostringstream
#include <string> // for string
template<class T>
T from_string(std::string const& str)
{
std::istringstream in(str);
T result;
if (in >> result)
return result;
else
throw "conversion_error";
}
#endif
#if 0
/*
* 3. 去除字符串首尾的空格
* */
std::string& trim(std::string &s)
{
if (s.empty())
{
return s;
}
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;
}
#endif
#if 0
/*
* 4. 读入换行符的getline函数
* */
int getline3_(char s[],int lim){
int c,i;
i=0;
while((c=getchar())!=EOF&&c!='\n'&&i<lim-1)
s[i++]=c;
if(c==EOF&&i==0)
return -1;
if(c=='\n')
s[i++]=c;
s[i]='\0';
return i;
}
#endif
#if 0
/*
* 5. 进行单词计数的小程序
*/
#include <stdio.h>
void word_count(FILE *f){
int c,nl,nw,nc,flag;
flag=0;
nl=nw=nc=0;
while((c=getc(f))!=EOF){
++nc;
if(c=='\n')
nl++;
if(c==' '||c=='\n'||c=='\t')
flag=0;
else if(!flag){
flag=1;
++nw;
}
}
printf("%3d %3d %3d\n",nl,nw,nc);
}
int main(){
word_count(stdin);
return 0;
}
#endif
#if 0
/*
* 6. 对文本进行简单的单词划分
* */
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void getword(vector<string>& words,string line,string sep=" :;,.\t\v\r\n\f[]{}()<>+-=*&^%$#@!~`\'\"|\\/?"){
string word;
string::size_type pos=0,pos2=0;
while((pos2=line.find_first_not_of(sep,pos))
!=string::npos){
pos=line.find_first_of(sep,pos2);
if(pos!=string::npos){
word=line.substr(pos2,pos-pos2);
}
else{
word=line.substr(pos2);
}
words.push_back(word);
}
}
int main(){
string line;
string sep(" :;,.\t\v\r\n\f[]{}()<>+-=*&^%$#@!~`\'\"|\\/?");
vector<string> words;
while(getline(cin,line)){
getword(words,line,sep);
}
vector<string>::iterator ite;
for(ite=words.begin();ite!=words.end();++ite)
cout<<*ite<<endl;
}
/*1. C++中整数/浮点等转化为字符串
*/
#include <ostream> // for the << operator
#include <sstream> // for ostringstream
#include <string> // for string
template<class T>
std::string to_string(T const& obj)
{
std::ostringstream out;
out << obj;
return out.str();
}
#endif
#if 0
/*
* 2. 从字符串得到整数/浮点数
* */
#include <istream> // for the >> operator
#include <sstream> // for ostringstream
#include <string> // for string
template<class T>
T from_string(std::string const& str)
{
std::istringstream in(str);
T result;
if (in >> result)
return result;
else
throw "conversion_error";
}
#endif
#if 0
/*
* 3. 去除字符串首尾的空格
* */
std::string& trim(std::string &s)
{
if (s.empty())
{
return s;
}
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;
}
#endif
#if 0
/*
* 4. 读入换行符的getline函数
* */
int getline3_(char s[],int lim){
int c,i;
i=0;
while((c=getchar())!=EOF&&c!='\n'&&i<lim-1)
s[i++]=c;
if(c==EOF&&i==0)
return -1;
if(c=='\n')
s[i++]=c;
s[i]='\0';
return i;
}
#endif
#if 0
/*
* 5. 进行单词计数的小程序
*/
#include <stdio.h>
void word_count(FILE *f){
int c,nl,nw,nc,flag;
flag=0;
nl=nw=nc=0;
while((c=getc(f))!=EOF){
++nc;
if(c=='\n')
nl++;
if(c==' '||c=='\n'||c=='\t')
flag=0;
else if(!flag){
flag=1;
++nw;
}
}
printf("%3d %3d %3d\n",nl,nw,nc);
}
int main(){
word_count(stdin);
return 0;
}
#endif
#if 0
/*
* 6. 对文本进行简单的单词划分
* */
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void getword(vector<string>& words,string line,string sep=" :;,.\t\v\r\n\f[]{}()<>+-=*&^%$#@!~`\'\"|\\/?"){
string word;
string::size_type pos=0,pos2=0;
while((pos2=line.find_first_not_of(sep,pos))
!=string::npos){
pos=line.find_first_of(sep,pos2);
if(pos!=string::npos){
word=line.substr(pos2,pos-pos2);
}
else{
word=line.substr(pos2);
}
words.push_back(word);
}
}
int main(){
string line;
string sep(" :;,.\t\v\r\n\f[]{}()<>+-=*&^%$#@!~`\'\"|\\/?");
vector<string> words;
while(getline(cin,line)){
getword(words,line,sep);
}
vector<string>::iterator ite;
for(ite=words.begin();ite!=words.end();++ite)
cout<<*ite<<endl;
}
#endif
2.
#if 0
/*
* 7. 利用vector对命令行参数的分析
*/
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using std::string;
using std::vector;
using std::endl;
using std::cout;
using std::ifstream;
class Arglist
{
public:
Arglist(size_t,char**);
size_t count() const;
const string& operator[](size_t)const;
private:
vector<string>args;
void expand(char*);
void add(char*);
};
Arglist::Arglist(size_t arg_count,char**arg_vec)
{
for(int i=0;i<arg_count;++i)
if(arg_vec[i][0]=='@')
expand(arg_vec[i]+1);
else
add(arg_vec[i]);
}
size_t Arglist::count()const
{
return args.size();
}
const string& Arglist::operator[](size_t i)const
{
return args[i];
}
void Arglist::add(char*arg)
{
args.push_back(arg);
}
void Arglist::expand(char*fname)
{
ifstream f(fname);
char token[64];
while(f>>token)
if(token[0]=='@')
expand(token+1);
else
add(token);
}
int main(int argc,char*argv[])
{
Arglist args(--argc,++argv);
for(int i=0;i<args.count();++i)
cout<<"arg["<<i<<"]=="<<args[i]<<endl;
}
#endif
#if 0
/*
* 8. 将文件按十六进制进行输出(多个文件)
*/
#include <stdio.h>
#include <ctype.h>
const int NBYTES=16;
void dump(FILE *f,char*s)
{
unsigned char buf[NBYTES];
int count;
long size=0L;
printf("Dump of %s:\n\n",s);
while((count=fread(buf,1,NBYTES,f))>0)
{
printf(" %06X ",size+=count);
for(int i=0;i<NBYTES;++i)
{
if(i==NBYTES/2)
putchar(' ');
if(i<count)
{
printf(" %02X",buf[i]);
if(!isprint(buf[i]))
buf[i]='.';
}
else
{
fputs(" ",stdout);
buf[i]=' ';
}
}
printf(" |%16.16s|\n",buf);
}
}
int main(int argc,char*argv[])
{
for(int i=1;i<argc;++i)
{
FILE *f;
if((f=fopen(argv[i],"rb"))==0)
fprintf(stderr,"Can't open %s\n",argv[i]);
else
{
dump(f,argv[i]);
fclose(f);
putchar('\f');
}
}
return 0;
}
#endif
#if 0
/*
* C++版本的使用十六进制显示文件:
*/
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const int NUM=16;
int main(int argc,char*argv[])
{
if(argc<2) {
cout<<"Usage:Display <filename> <filename> ..."<<endl;
return 1;
}
int i=1;
do{
ifstream in(argv[i]);
if(!in)
{
cout<<"Cannot open file:"<<argv[i]<<endl;
continue;
}
char line[NUM];
int count=0;
int j,k;
cout.setf(ios::uppercase);
cout<<"File:"<<argv[i]<<endl;
while(!in.eof())
{
for(j=0;j<NUM&&!in.eof();++j)
in.get(line[j]);
if(j<NUM)
j--;
for(k=0;k<j;k++)
cout<<setw(3)<<hex<<(int)line[k];
for(;k<16;k++)
cout<<setw(3)<<" ";
cout<<"\t";
for(k=0;k<j;k++)
if(isprint(line[k]))
cout<<line[k];
else
cout<<".";
cout<<endl;
count++;
if(count==16){
count=0;
cout<<"Press ENTER to continue:";
cin.get();
cout<<endl;
}
}
in.close();
i++;
}while(i<argc);
return 0;
}
#endif
#if 0
/*
* 9. 十六进制字符串转化为数字的三种方法
* */
#include <stdio.h>
long atox(char*s)
{
long sum;
int digit;
while(isspace(*s))
++s;
for(sum=0L;isxdigit(*s);++s)
{
if(isdigit(*s))
digit=*s-'0';
else
digit=toupper(*s)-'A'+10;
sum=sum*16L+digit;
}
return sum;
}
long atox2(char*s)
{
static char xdigits[]="0123456789ABCDEF";
long sum;
int digit;
while(isspace(*s))
++s;
for(sum=0L;isxdigit(*s);++s)
{
digit=strchr(xdigits,toupper(*s))-xdigits;
sum=sum*16L+digit;
}
return sum;
}
long atox3(char*s)
{
int sum;
sscanf(s,"%x",&sum);
return sum;
}
int main(int argc,char*argv[])
{
char *s;
int value;
s=argv[1];
value=atox(s);
printf("%s %d\n",s,value);
return 0;
}
#endif
#if 0
/*
* 10. C语言中利用strtok对字符串根据特定的字符进行划分
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getword(char* words[],char *line,const char* delim){
int count;
char* token;
count=0;
token=strtok(line,delim);
words[count++]=token;
while((token=strtok(NULL,delim))!=NULL)
words[count++]=token;
return count;
}
void strtok1()
{
char *path="/etc/passwd";
char buf[BUFSIZ];
char *words[100];
char *delim=":/";
FILE* fp=fopen(path,"r");
if(!fp)
{
printf("Can't open file:%s\n",path);
exit(-1);
}
while(fgets(buf,BUFSIZ,fp))
{
printf("%s",buf);
int count=getword(words,buf,delim);
int i;
if(count>0)
for(i=0;i<count;i++)
printf("---->%s\n",words[i]);
}
fclose(fp);
}
int main()
{
strtok1();
}
#endif
/*
* 7. 利用vector对命令行参数的分析
*/
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using std::string;
using std::vector;
using std::endl;
using std::cout;
using std::ifstream;
class Arglist
{
public:
Arglist(size_t,char**);
size_t count() const;
const string& operator[](size_t)const;
private:
vector<string>args;
void expand(char*);
void add(char*);
};
Arglist::Arglist(size_t arg_count,char**arg_vec)
{
for(int i=0;i<arg_count;++i)
if(arg_vec[i][0]=='@')
expand(arg_vec[i]+1);
else
add(arg_vec[i]);
}
size_t Arglist::count()const
{
return args.size();
}
const string& Arglist::operator[](size_t i)const
{
return args[i];
}
void Arglist::add(char*arg)
{
args.push_back(arg);
}
void Arglist::expand(char*fname)
{
ifstream f(fname);
char token[64];
while(f>>token)
if(token[0]=='@')
expand(token+1);
else
add(token);
}
int main(int argc,char*argv[])
{
Arglist args(--argc,++argv);
for(int i=0;i<args.count();++i)
cout<<"arg["<<i<<"]=="<<args[i]<<endl;
}
#endif
#if 0
/*
* 8. 将文件按十六进制进行输出(多个文件)
*/
#include <stdio.h>
#include <ctype.h>
const int NBYTES=16;
void dump(FILE *f,char*s)
{
unsigned char buf[NBYTES];
int count;
long size=0L;
printf("Dump of %s:\n\n",s);
while((count=fread(buf,1,NBYTES,f))>0)
{
printf(" %06X ",size+=count);
for(int i=0;i<NBYTES;++i)
{
if(i==NBYTES/2)
putchar(' ');
if(i<count)
{
printf(" %02X",buf[i]);
if(!isprint(buf[i]))
buf[i]='.';
}
else
{
fputs(" ",stdout);
buf[i]=' ';
}
}
printf(" |%16.16s|\n",buf);
}
}
int main(int argc,char*argv[])
{
for(int i=1;i<argc;++i)
{
FILE *f;
if((f=fopen(argv[i],"rb"))==0)
fprintf(stderr,"Can't open %s\n",argv[i]);
else
{
dump(f,argv[i]);
fclose(f);
putchar('\f');
}
}
return 0;
}
#endif
#if 0
/*
* C++版本的使用十六进制显示文件:
*/
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const int NUM=16;
int main(int argc,char*argv[])
{
if(argc<2) {
cout<<"Usage:Display <filename> <filename> ..."<<endl;
return 1;
}
int i=1;
do{
ifstream in(argv[i]);
if(!in)
{
cout<<"Cannot open file:"<<argv[i]<<endl;
continue;
}
char line[NUM];
int count=0;
int j,k;
cout.setf(ios::uppercase);
cout<<"File:"<<argv[i]<<endl;
while(!in.eof())
{
for(j=0;j<NUM&&!in.eof();++j)
in.get(line[j]);
if(j<NUM)
j--;
for(k=0;k<j;k++)
cout<<setw(3)<<hex<<(int)line[k];
for(;k<16;k++)
cout<<setw(3)<<" ";
cout<<"\t";
for(k=0;k<j;k++)
if(isprint(line[k]))
cout<<line[k];
else
cout<<".";
cout<<endl;
count++;
if(count==16){
count=0;
cout<<"Press ENTER to continue:";
cin.get();
cout<<endl;
}
}
in.close();
i++;
}while(i<argc);
return 0;
}
#endif
#if 0
/*
* 9. 十六进制字符串转化为数字的三种方法
* */
#include <stdio.h>
long atox(char*s)
{
long sum;
int digit;
while(isspace(*s))
++s;
for(sum=0L;isxdigit(*s);++s)
{
if(isdigit(*s))
digit=*s-'0';
else
digit=toupper(*s)-'A'+10;
sum=sum*16L+digit;
}
return sum;
}
long atox2(char*s)
{
static char xdigits[]="0123456789ABCDEF";
long sum;
int digit;
while(isspace(*s))
++s;
for(sum=0L;isxdigit(*s);++s)
{
digit=strchr(xdigits,toupper(*s))-xdigits;
sum=sum*16L+digit;
}
return sum;
}
long atox3(char*s)
{
int sum;
sscanf(s,"%x",&sum);
return sum;
}
int main(int argc,char*argv[])
{
char *s;
int value;
s=argv[1];
value=atox(s);
printf("%s %d\n",s,value);
return 0;
}
#endif
#if 0
/*
* 10. C语言中利用strtok对字符串根据特定的字符进行划分
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getword(char* words[],char *line,const char* delim){
int count;
char* token;
count=0;
token=strtok(line,delim);
words[count++]=token;
while((token=strtok(NULL,delim))!=NULL)
words[count++]=token;
return count;
}
void strtok1()
{
char *path="/etc/passwd";
char buf[BUFSIZ];
char *words[100];
char *delim=":/";
FILE* fp=fopen(path,"r");
if(!fp)
{
printf("Can't open file:%s\n",path);
exit(-1);
}
while(fgets(buf,BUFSIZ,fp))
{
printf("%s",buf);
int count=getword(words,buf,delim);
int i;
if(count>0)
for(i=0;i<count;i++)
printf("---->%s\n",words[i]);
}
fclose(fp);
}
int main()
{
strtok1();
}
#endif
3.
#if 0
/*
* 11. C语言动态链接
*/
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main()
{
void *handle;
void (*errfcn)(const char*fmt,...);
const char *errmsg;
FILE* pf;
handle=dlopen("./liberr.so",RTLD_NOW);
if(handle==NULL){
fprintf(stderr,"Failed to load liberr.so:%s\n",dlerror());
exit(EXIT_FAILURE);
}
dlerror();
errfcn=dlsym(handle,"err_ret");
if((errmsg=dlerror())!=NULL){
fprintf(stderr,"Didn't find err_ret:%s\n",errmsg);
exit(EXIT_FAILURE);
}
if((pf=fopen("foobar","r"))==NULL){
errfcn("Couldn't open foobar");
}
dlclose(handle);
exit(EXIT_SUCCESS);
}
#endif
#if 0
/*
* 14. 一个简单的文件查看程序view
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#define NMAX 100
#define NROWS 24
#define NCOLS 79
#define HORIZ 20
#define RANDOM() rand()%NMAX
// defination of stack
typedef fpos_t TYPE;
TYPE stack[NMAX];
int _top;
void init();
int empty();
void push(TYPE p);
TYPE pop();
TYPE top();
int full();
char screen[NROWS][BUFSIZ];
size_t nlines,offset=0;
void read_a_screen(FILE*f)
{
int i;
clearerr(f);
for(i=0;i<NROWS&&fgets(screen[i],BUFSIZ,f);i++)
screen[i][strlen(screen[i])-1]='\0';
nlines=i;
}
void display()
{
int i;
for(i=0;i<nlines;i++)
if(offset<strlen(screen[i]))
fprintf(stdout,"%-.*s\n",NCOLS,screen[i]+offset);
else
fputc('\n',stdout);
}
int main(int argc,char**argv)
{
FILE*f;
fpos_t top_pos;
if(argc<2)
{
printf("Too few arguments\n");
return -1;
}
if(NULL==(f=fopen(argv[1],"r")))
{
printf("Can't open the file:%s\n",argv[1]);
return -1;
}
init();
TOP:
rewind(f);
fgetpos(f,&top_pos);
read_a_screen(f);
display();
for(;;)
{
int c=getchar();
switch(toupper(c))
{
case 'N':
if(!feof(f)) {
push(top_pos);
fgetpos(f,&top_pos);
read_a_screen(f);
}
display();
break;
case 'P':
if(!empty()) {
top_pos=pop();
fsetpos(f,&top_pos);
read_a_screen(f);
}
display();
break;
case 'T':
while(!empty())
pop();
goto TOP;
break;
case 'B':
while(!feof(f)) {
push(top_pos);
fgetpos(f,&top_pos);
read_a_screen(f);
}
display();
break;
case 'L':
if(offset>0)
offset-=HORIZ;
display();
break;
case 'R':
if(offset<BUFSIZ-HORIZ)
offset+=HORIZ;
display();
break;
case 'Q':
return 0;
}
}
return 0;
}
void init() {
_top=-1;
}
int empty() {
return _top==-1;
}
void push(TYPE p) {
stack[++_top]=p;
}
TYPE pop() {
return stack[_top--];
}
TYPE top() {
return stack[_top];
}
int full() {
return _top==NMAX-1;
}
#endif
#if 0
13. C语言中strstr程序的实现
#include <stdio.h>
#include <stdlib.h>
const char *strstr(const char *str1,const char *str2){
const char *p=str1;
const char *q;
while(*p!='\0'){
const char *p1=p;
q=str2;
while(*q!='\0'){
if(*q!=*p1)
break;
p1++;
q++;
}
if(*q=='\0')
return p;
p++;
}
return NULL;
}
int strstr2(const char *str1,const char *str2){
int i=0;
int j=0;
while(str1[i]!='\0'&&str2[j]!='\0'){
if(str1[i]==str2[j]){
i++;
j++;
}
else{
i=i-j+1;
j=0;
}
}
if(str2[j]=='\0'){
return 1;
}
else{
return 0;
}
}
int main()
{
int i;
char *a="abcabcdefgh";
char *b="bcdf";
const char *p=strstr(a,b);
if(p!=NULL)
printf("%s\n",p);
else
printf("not matched\n");
i=strstr2(a,b);
printf("%d\n",i);
return 0;
}
#endif
#if 0
/*
* 14. 常见字符串操作函数
*/
#include <stdio.h>
#include <string.h>
//#include <unistd.h>
#define toupper_(a) ((a)>='a'&&(a)<='z'?(a)+'A'-'a':(a))
#define tolower_(a) ((a)>='A'&&(a)<='Z'?(a)+'a'-'A':(a))
#define isalnum_(c) ((toupper_((c))>='A')&&(toupper((c))<='Z')||((c)>='0')&&((c)<='9'))
#define isalpha_(c) ((toupper_((c))>='A')&&(toupper((c))<='Z'))
#define isdigit_(c) (((c)>='0')&&((c)<='9'))
#define isascii_(c) ((unsigned)(c)<128)
#define isgraph_(c) (((c)>=33)&&((c)<=127))
#define islower_(c) (((c)>='a')&&((c)<='z'))
#define isupper_(c) (((c)>='A')&&((c)<='Z'))
#define isprint_(c) (((c)>=32)&&((c)<=127))
#define ispunct_(c) (isgraph_((c))&&!isalnum_((c)))
#define isspace_(c) (((c)==32)||((c)==9)||((c)==13))
#define isxdigit_(c) (isdigit_((c))||(toupper_((c))>='A'&&toupper_((c))<='F'))
#define toascii_(c) ((c)&0x7f)
//判断字符串的长度
size_t strlen_(const char *str) {
size_t i=0;
while(str[i])
i++;
return i;
}
//将一个串的内容追加到另一个串上
char *strcat_(char*tgt,const char*src) {
char*p=tgt;
while(*tgt)
tgt++;
while(*tgt++=*src++)
;
return p;
} char *strncat_(char*tgt,const char*src,int n)
{
int i=0;
char*p=tgt;
while(*tgt)
tgt++;
while((i++<n)&&(*tgt++=*src++))
;
if(i>n)
*tgt='\0';
return p;
}
//将一个字符串的字符复制到另一个字符串中
char *strcpy_(char*dest,const char*src) {
while(*dest++=*src++)
;
return dest-1;
}
char *strncpy_(char*dest,const char*src,int n) {
int i=0;
while((i++<n)&&(*dest++=*src++))
;
if(i>n)
*dest='\0';
return dest-1;
}
//判断两个字符串是否相同
int streql(const char*str1,const char*str2){
while((*str1==*str2)&&(*str1))
{
str1++;
str2++;
}
return (*str1=='\0')&&(*str2=='\0');
}
//比较字符串时忽略大小写
int strieql(const char*str1,const char*str2){
while((toupper_(*str1)==toupper_(*str2))&&(*str1))
{
str1++;
str2++;
}
return (*str1=='\0')&&(*str2=='\0');
}
//将字符串转换成大写或小写
char* strlwr_(char*str) {
char*p=str;
while(*str)
{
*str=tolower_(*str);
str++;
}
return p;
}
char* strupr_(char*str) {
char*p=str;
while(*str)
{
*str=toupper_(*str);
str++;
}
return p;
}
//获取字符串中第一次出现的某个字符
char* strchr_(char*str,char c) {
while((*str!=c)&&(*str))
str++;
return str;
}
//返回索引到串的首次出现
int strchr_i(const char*str,char c) {
int i=0;
while((str[i]!=c)&&(str[i]))
i++;
return (str[i]?i:-1);
}
//搜索字符在字符串中的末次出现
char* strrchr_(char*str,char c) {
char*p=NULL;
while(*str)
{
if(*str==c)
p=str;
str++;
}
return p;
}
//返回指向字符中末次出现的索引
int strrchr_i(const char*str,char c) {
int p=-1;
int i=0;
while(str[i])
{
if(str[i]==c)
p=i;
i++;
}
return p;
}
//计算字符串的内容反转
char* strrev_(char*str) {
char*org=str;
char*forward=str;
while(*str)
str++;
str--;
while(forward<str) {
char tmp=*str;
*str=*forward;
*forward=tmp;
forward++;
str--;
}
return org;
}
//比较两个字符串
int strcmp_(const char*str1,const char*str2){
while((*str1==*str2)&&(*str1))
{
str1++;
str2++;
}
if((*str1==*str2)&&(!*str1))
return 0;
else if((*str1)&&(!*str2))
return -1;
else if((!*str1)&&(*str2))
return 1;
else
return (*str1>*str2?-1:1);
}
//比较两个字符中的前N个字符
int strncmp_(const char*str1,const char*str2,int n){
int i=0;
while((i<n)&&(str1[i]==str2[i])&&(str1[i]))
{
i++;
}
if(i==n)
return 0;
else if(str1[i]==str2[i]&&!str1[i])
return 0;
else if((str1[i])&&(!str2[i]))
return -1;
else if((!str1[i])&&(str2[i]))
return 1;
else
return (str1[i]>str2[i]?-1:1);
}
//从给定字符序列中查找字符的首次出现
size_t strspn_(const char*s1,const char*s2) {
int i=0;
int j;
int sz1=strlen(s1);
int sz2=strlen(s2);
while(i<sz1)
{
j=0;
while(j<sz2)
{
if(s2[i]==s1[j])
break;
j++;
}
if(j==sz2)
return i;
i++;
}
return i;
}
//在字符串中查找子字符串
char* strstr_(const char*s1,const char *s2) {
while(*s1!='\0')
{
char*p=s1;
char *q=s2;
while(*q==*p&&*q)
{
p++;
q++;
}
if(*q=='\0')
return s1;
s1++;
}
return NULL;
}
//计算子字符串出现的次数
int strstr_cnt(const char*s1,const char *s2) {
int count=0;
while(*s1!='\0')
{
char*p=s1;
char *q=s2;
while(*q==*p&&*q)
{
p++;
q++;
}
if(*q=='\0')
count++;
s1++;
}
return count;
}
//给子字符串获取索引
int strstr_i(const char*s1,const char *s2) {
char*org=s1;
while(*s1!='\0')
{
char*p=s1;
char *q=s2;
while(*q==*p&&*q)
{
p++;
q++;
}
if(*q=='\0')
return (s1-org);
s1++;
}
return -1;
}
//获取子字符串的最右端出现
char* strrstr_(const char*s1,const char *s2) {
char* t=NULL;
while(*s1!='\0')
{
char*p=s1;
char *q=s2;
while(*q==*p&&*q)
{
p++;
q++;
}
if(*q=='\0')
t=s1;
s1++;
}
return t;
}
//
char* strstr_rem(char*str,char*substr) {
char*org=str;
char*p=NULL;
while(*str!='\0')
{
p=str;
char*q=substr;
while(*q!='\0')
{
if(*p!=*q)
break;
p++;
q++;
}
if(*q=='\0')
break;
str++;
}
if(*str!='\0')
strcpy_(org,p);
return str;
}
int main()
{
// char* a="hello";
// char b[]="world";
// char dest[200];
// strcat(strcpy(strcpy(dest,a)," k,"),b);
// printf("%s\n",dest);
// printf("%d\n",strlen(a));
// printf("%d\n",sizeof(b));
// printf("%d\n",strieql("abc","ABC"));
// printf("%d\n",streql("Abc","Abc"));
//char buf[100];
//strcpy(buf,a);
//int i;
//char *p;
//getcwd(buf,100);
//printf("%s\n",buf);
//char *buf2=get_current_dir_name();
//printf("%s\n",buf2);
//free(buf2);
//p=strchr_(buf,'/');
//printf("%s\n",p);
//i=strchr_i(buf,'/');
//printf("%d\n",i);
//p=strrchr_(buf,'/');
//printf("%s\n",p);
//i=strrchr_i(buf,'/');
//printf("%d\n",i);
//strrev_(buf);
//printf("%s\n",buf);
//
//printf("%d\n",strncmp_("abc","abcdef",3));
//printf("%d\n",strncmp_("abc","bcdef",3));
//printf("%d\n",strncmp_("abcdefg","abcdef",10));
// printf("%s\n",strstr_("AbcDef","Abc"));
// printf("%s\n",strstr_("AbcDef","Def"));
// printf("%s\n",strstr_("AbcAbc","Def")?"over":"NULL");
char p[]="AbcDef";
char q[]="Abc";
printf("%s\n",p);
strstr_rem(p,q);
printf("%s\n",p);
return 0;
}
#endif
#if 0
/*
* 15. RTTI的使用
*/
#include <iostream>
#include <typeinfo>
#include <ctime>
#include <cstdlib>
using std::cout;
using std::endl;
class Mammal {
public:
virtual bool lays_eggs() { return false; } // Mammal is polymorphic
// ...
};
class Dog: public Mammal {
public:
// ...
};
class Cat: public Mammal {
public:
// ...
};
class Platypus: public Mammal {
public:
bool lays_eggs() { return true; }
// ...
};
Mammal *factory(int i)
{
switch(i%3){
case 0:return new Dog;
case 1:return new Cat;
case 2:return new Platypus;
}
return 0;
}
int main()
{
Mammal *ptr;
int c=0,d=0,p=0;
srand((int)time(NULL));
for(int i=0;i<10;i++){
int value=rand()%100;
ptr=factory(value);
cout<<"Object is "<<typeid(*ptr).name()<<endl;
if(typeid(*ptr)==typeid(Dog))
d++;
if(typeid(*ptr)==typeid(Cat))
c++;
if(typeid(*ptr)==typeid(Platypus))
p++;
}
cout<<"Animals generated:"<<endl;
cout<<"Dogs:"<<d<<endl;
cout<<"Cats:"<<c<<endl;
cout<<"Platypuses:"<<p<<endl;
return 0;
}
#endif
/*
* 11. C语言动态链接
*/
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main()
{
void *handle;
void (*errfcn)(const char*fmt,...);
const char *errmsg;
FILE* pf;
handle=dlopen("./liberr.so",RTLD_NOW);
if(handle==NULL){
fprintf(stderr,"Failed to load liberr.so:%s\n",dlerror());
exit(EXIT_FAILURE);
}
dlerror();
errfcn=dlsym(handle,"err_ret");
if((errmsg=dlerror())!=NULL){
fprintf(stderr,"Didn't find err_ret:%s\n",errmsg);
exit(EXIT_FAILURE);
}
if((pf=fopen("foobar","r"))==NULL){
errfcn("Couldn't open foobar");
}
dlclose(handle);
exit(EXIT_SUCCESS);
}
#endif
#if 0
/*
* 14. 一个简单的文件查看程序view
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#define NMAX 100
#define NROWS 24
#define NCOLS 79
#define HORIZ 20
#define RANDOM() rand()%NMAX
// defination of stack
typedef fpos_t TYPE;
TYPE stack[NMAX];
int _top;
void init();
int empty();
void push(TYPE p);
TYPE pop();
TYPE top();
int full();
char screen[NROWS][BUFSIZ];
size_t nlines,offset=0;
void read_a_screen(FILE*f)
{
int i;
clearerr(f);
for(i=0;i<NROWS&&fgets(screen[i],BUFSIZ,f);i++)
screen[i][strlen(screen[i])-1]='\0';
nlines=i;
}
void display()
{
int i;
for(i=0;i<nlines;i++)
if(offset<strlen(screen[i]))
fprintf(stdout,"%-.*s\n",NCOLS,screen[i]+offset);
else
fputc('\n',stdout);
}
int main(int argc,char**argv)
{
FILE*f;
fpos_t top_pos;
if(argc<2)
{
printf("Too few arguments\n");
return -1;
}
if(NULL==(f=fopen(argv[1],"r")))
{
printf("Can't open the file:%s\n",argv[1]);
return -1;
}
init();
TOP:
rewind(f);
fgetpos(f,&top_pos);
read_a_screen(f);
display();
for(;;)
{
int c=getchar();
switch(toupper(c))
{
case 'N':
if(!feof(f)) {
push(top_pos);
fgetpos(f,&top_pos);
read_a_screen(f);
}
display();
break;
case 'P':
if(!empty()) {
top_pos=pop();
fsetpos(f,&top_pos);
read_a_screen(f);
}
display();
break;
case 'T':
while(!empty())
pop();
goto TOP;
break;
case 'B':
while(!feof(f)) {
push(top_pos);
fgetpos(f,&top_pos);
read_a_screen(f);
}
display();
break;
case 'L':
if(offset>0)
offset-=HORIZ;
display();
break;
case 'R':
if(offset<BUFSIZ-HORIZ)
offset+=HORIZ;
display();
break;
case 'Q':
return 0;
}
}
return 0;
}
void init() {
_top=-1;
}
int empty() {
return _top==-1;
}
void push(TYPE p) {
stack[++_top]=p;
}
TYPE pop() {
return stack[_top--];
}
TYPE top() {
return stack[_top];
}
int full() {
return _top==NMAX-1;
}
#endif
#if 0
13. C语言中strstr程序的实现
#include <stdio.h>
#include <stdlib.h>
const char *strstr(const char *str1,const char *str2){
const char *p=str1;
const char *q;
while(*p!='\0'){
const char *p1=p;
q=str2;
while(*q!='\0'){
if(*q!=*p1)
break;
p1++;
q++;
}
if(*q=='\0')
return p;
p++;
}
return NULL;
}
int strstr2(const char *str1,const char *str2){
int i=0;
int j=0;
while(str1[i]!='\0'&&str2[j]!='\0'){
if(str1[i]==str2[j]){
i++;
j++;
}
else{
i=i-j+1;
j=0;
}
}
if(str2[j]=='\0'){
return 1;
}
else{
return 0;
}
}
int main()
{
int i;
char *a="abcabcdefgh";
char *b="bcdf";
const char *p=strstr(a,b);
if(p!=NULL)
printf("%s\n",p);
else
printf("not matched\n");
i=strstr2(a,b);
printf("%d\n",i);
return 0;
}
#endif
#if 0
/*
* 14. 常见字符串操作函数
*/
#include <stdio.h>
#include <string.h>
//#include <unistd.h>
#define toupper_(a) ((a)>='a'&&(a)<='z'?(a)+'A'-'a':(a))
#define tolower_(a) ((a)>='A'&&(a)<='Z'?(a)+'a'-'A':(a))
#define isalnum_(c) ((toupper_((c))>='A')&&(toupper((c))<='Z')||((c)>='0')&&((c)<='9'))
#define isalpha_(c) ((toupper_((c))>='A')&&(toupper((c))<='Z'))
#define isdigit_(c) (((c)>='0')&&((c)<='9'))
#define isascii_(c) ((unsigned)(c)<128)
#define isgraph_(c) (((c)>=33)&&((c)<=127))
#define islower_(c) (((c)>='a')&&((c)<='z'))
#define isupper_(c) (((c)>='A')&&((c)<='Z'))
#define isprint_(c) (((c)>=32)&&((c)<=127))
#define ispunct_(c) (isgraph_((c))&&!isalnum_((c)))
#define isspace_(c) (((c)==32)||((c)==9)||((c)==13))
#define isxdigit_(c) (isdigit_((c))||(toupper_((c))>='A'&&toupper_((c))<='F'))
#define toascii_(c) ((c)&0x7f)
//判断字符串的长度
size_t strlen_(const char *str) {
size_t i=0;
while(str[i])
i++;
return i;
}
//将一个串的内容追加到另一个串上
char *strcat_(char*tgt,const char*src) {
char*p=tgt;
while(*tgt)
tgt++;
while(*tgt++=*src++)
;
return p;
} char *strncat_(char*tgt,const char*src,int n)
{
int i=0;
char*p=tgt;
while(*tgt)
tgt++;
while((i++<n)&&(*tgt++=*src++))
;
if(i>n)
*tgt='\0';
return p;
}
//将一个字符串的字符复制到另一个字符串中
char *strcpy_(char*dest,const char*src) {
while(*dest++=*src++)
;
return dest-1;
}
char *strncpy_(char*dest,const char*src,int n) {
int i=0;
while((i++<n)&&(*dest++=*src++))
;
if(i>n)
*dest='\0';
return dest-1;
}
//判断两个字符串是否相同
int streql(const char*str1,const char*str2){
while((*str1==*str2)&&(*str1))
{
str1++;
str2++;
}
return (*str1=='\0')&&(*str2=='\0');
}
//比较字符串时忽略大小写
int strieql(const char*str1,const char*str2){
while((toupper_(*str1)==toupper_(*str2))&&(*str1))
{
str1++;
str2++;
}
return (*str1=='\0')&&(*str2=='\0');
}
//将字符串转换成大写或小写
char* strlwr_(char*str) {
char*p=str;
while(*str)
{
*str=tolower_(*str);
str++;
}
return p;
}
char* strupr_(char*str) {
char*p=str;
while(*str)
{
*str=toupper_(*str);
str++;
}
return p;
}
//获取字符串中第一次出现的某个字符
char* strchr_(char*str,char c) {
while((*str!=c)&&(*str))
str++;
return str;
}
//返回索引到串的首次出现
int strchr_i(const char*str,char c) {
int i=0;
while((str[i]!=c)&&(str[i]))
i++;
return (str[i]?i:-1);
}
//搜索字符在字符串中的末次出现
char* strrchr_(char*str,char c) {
char*p=NULL;
while(*str)
{
if(*str==c)
p=str;
str++;
}
return p;
}
//返回指向字符中末次出现的索引
int strrchr_i(const char*str,char c) {
int p=-1;
int i=0;
while(str[i])
{
if(str[i]==c)
p=i;
i++;
}
return p;
}
//计算字符串的内容反转
char* strrev_(char*str) {
char*org=str;
char*forward=str;
while(*str)
str++;
str--;
while(forward<str) {
char tmp=*str;
*str=*forward;
*forward=tmp;
forward++;
str--;
}
return org;
}
//比较两个字符串
int strcmp_(const char*str1,const char*str2){
while((*str1==*str2)&&(*str1))
{
str1++;
str2++;
}
if((*str1==*str2)&&(!*str1))
return 0;
else if((*str1)&&(!*str2))
return -1;
else if((!*str1)&&(*str2))
return 1;
else
return (*str1>*str2?-1:1);
}
//比较两个字符中的前N个字符
int strncmp_(const char*str1,const char*str2,int n){
int i=0;
while((i<n)&&(str1[i]==str2[i])&&(str1[i]))
{
i++;
}
if(i==n)
return 0;
else if(str1[i]==str2[i]&&!str1[i])
return 0;
else if((str1[i])&&(!str2[i]))
return -1;
else if((!str1[i])&&(str2[i]))
return 1;
else
return (str1[i]>str2[i]?-1:1);
}
//从给定字符序列中查找字符的首次出现
size_t strspn_(const char*s1,const char*s2) {
int i=0;
int j;
int sz1=strlen(s1);
int sz2=strlen(s2);
while(i<sz1)
{
j=0;
while(j<sz2)
{
if(s2[i]==s1[j])
break;
j++;
}
if(j==sz2)
return i;
i++;
}
return i;
}
//在字符串中查找子字符串
char* strstr_(const char*s1,const char *s2) {
while(*s1!='\0')
{
char*p=s1;
char *q=s2;
while(*q==*p&&*q)
{
p++;
q++;
}
if(*q=='\0')
return s1;
s1++;
}
return NULL;
}
//计算子字符串出现的次数
int strstr_cnt(const char*s1,const char *s2) {
int count=0;
while(*s1!='\0')
{
char*p=s1;
char *q=s2;
while(*q==*p&&*q)
{
p++;
q++;
}
if(*q=='\0')
count++;
s1++;
}
return count;
}
//给子字符串获取索引
int strstr_i(const char*s1,const char *s2) {
char*org=s1;
while(*s1!='\0')
{
char*p=s1;
char *q=s2;
while(*q==*p&&*q)
{
p++;
q++;
}
if(*q=='\0')
return (s1-org);
s1++;
}
return -1;
}
//获取子字符串的最右端出现
char* strrstr_(const char*s1,const char *s2) {
char* t=NULL;
while(*s1!='\0')
{
char*p=s1;
char *q=s2;
while(*q==*p&&*q)
{
p++;
q++;
}
if(*q=='\0')
t=s1;
s1++;
}
return t;
}
//
char* strstr_rem(char*str,char*substr) {
char*org=str;
char*p=NULL;
while(*str!='\0')
{
p=str;
char*q=substr;
while(*q!='\0')
{
if(*p!=*q)
break;
p++;
q++;
}
if(*q=='\0')
break;
str++;
}
if(*str!='\0')
strcpy_(org,p);
return str;
}
int main()
{
// char* a="hello";
// char b[]="world";
// char dest[200];
// strcat(strcpy(strcpy(dest,a)," k,"),b);
// printf("%s\n",dest);
// printf("%d\n",strlen(a));
// printf("%d\n",sizeof(b));
// printf("%d\n",strieql("abc","ABC"));
// printf("%d\n",streql("Abc","Abc"));
//char buf[100];
//strcpy(buf,a);
//int i;
//char *p;
//getcwd(buf,100);
//printf("%s\n",buf);
//char *buf2=get_current_dir_name();
//printf("%s\n",buf2);
//free(buf2);
//p=strchr_(buf,'/');
//printf("%s\n",p);
//i=strchr_i(buf,'/');
//printf("%d\n",i);
//p=strrchr_(buf,'/');
//printf("%s\n",p);
//i=strrchr_i(buf,'/');
//printf("%d\n",i);
//strrev_(buf);
//printf("%s\n",buf);
//
//printf("%d\n",strncmp_("abc","abcdef",3));
//printf("%d\n",strncmp_("abc","bcdef",3));
//printf("%d\n",strncmp_("abcdefg","abcdef",10));
// printf("%s\n",strstr_("AbcDef","Abc"));
// printf("%s\n",strstr_("AbcDef","Def"));
// printf("%s\n",strstr_("AbcAbc","Def")?"over":"NULL");
char p[]="AbcDef";
char q[]="Abc";
printf("%s\n",p);
strstr_rem(p,q);
printf("%s\n",p);
return 0;
}
#endif
#if 0
/*
* 15. RTTI的使用
*/
#include <iostream>
#include <typeinfo>
#include <ctime>
#include <cstdlib>
using std::cout;
using std::endl;
class Mammal {
public:
virtual bool lays_eggs() { return false; } // Mammal is polymorphic
// ...
};
class Dog: public Mammal {
public:
// ...
};
class Cat: public Mammal {
public:
// ...
};
class Platypus: public Mammal {
public:
bool lays_eggs() { return true; }
// ...
};
Mammal *factory(int i)
{
switch(i%3){
case 0:return new Dog;
case 1:return new Cat;
case 2:return new Platypus;
}
return 0;
}
int main()
{
Mammal *ptr;
int c=0,d=0,p=0;
srand((int)time(NULL));
for(int i=0;i<10;i++){
int value=rand()%100;
ptr=factory(value);
cout<<"Object is "<<typeid(*ptr).name()<<endl;
if(typeid(*ptr)==typeid(Dog))
d++;
if(typeid(*ptr)==typeid(Cat))
c++;
if(typeid(*ptr)==typeid(Platypus))
p++;
}
cout<<"Animals generated:"<<endl;
cout<<"Dogs:"<<d<<endl;
cout<<"Cats:"<<c<<endl;
cout<<"Platypuses:"<<p<<endl;
return 0;
}
#endif
4.
#if 0
/*
* 16. 简单的词典查询
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char *dic[]={
"atlas","A voluem of maps.",
"car","A motorized vechicle.",
"telephone","A communication device.",
"airplane","A flying machine.",
"","",
};
int main()
{
char word[80];
char **p;
do{
puts("Enter the word:");
scanf("%s",word);
p=(char**)dic;
do{
if(!strcmp(*p,word))
{
puts("Meaning:");
puts(*(p+1));
break;
}
p=p+2;
}while(*p);
if(!*p)
puts("Not found.");
puts("Another word?");
scanf("%s",word);
}while(word[0]=='Y'||word[0]=='y');
return 0;
}
#endif
#if 0
/*
* 18. 洗牌程序 版本-1
*/
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::endl;
using std::setw;
using std::ios;
using std::setiosflags;
void shuffle(int [][13]);
void deal(const int[][13],const char*[],const char*[]);
int main()
{
const char* suit[4]={"Hearts","Diamonds","Clubs","Spades"};
const char *face[13]={
"Ace","Deuce","Three","Four","Five",
"Six","Seven","Eight","Nine","Ten",
"Jack","Queen","King",
};
int deck[4][13]={0};
srand((int)time(NULL));
shuffle(deck);
deal(deck,suit,face);
return 0;
}
void shuffle(int deck[][13])
{
for(int i=1;i<=52;i++)
{
int row;
int col;
do
{
row=rand()%4;
col=rand()%13;
}while(deck[row][col]!=0);
deck[row][col]=i;
}
}
void deal(const int deck[][13],const char* suit[],const char* face[])
{
for(int i=1;i<=52;i++)
{
for(int j=0;j<4;j++)
{
for(int k=0;k<13;k++)
if(deck[j][k]==i)
{
cout<<setw(5)<<setiosflags(ios::right)
<<face[k]<<" of "
<<setw(8)<<setiosflags(ios::left)
<<suit[j]
<<(i%2==0?'\n':'\t');
goto L;
}
}
L:
;
}
}
#endif
#if 0
/*
* 版本-2
* 结构体
*/
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::endl;
using std::setw;
using std::ios;
struct Card {
const char *face;
const char *suit;
};
void fillDeck(Card*,const char*[],const char*[]);
void shuffle(Card*);
void deal(Card*);
int main()
{
Card deck[52];
const char* suit[4]={"Hearts","Diamonds","Clubs","Spades"};
const char *face[13]={
"Ace","Deuce","Three","Four","Five",
"Six","Seven","Eight","Nine","Ten",
"Jack","Queen","King",
};
srand(time(0));
fillDeck(deck,face,suit);
shuffle(deck);
deal(deck);
return 0;
}
void fillDeck(Card*wDeck,const char*wFace[],const char*wSuit[])
{
for(int i=0;i<52;i++)
{
wDeck[i].face=wFace[i%13];
wDeck[i].suit=wSuit[i/13];
}
}
void shuffle(Card*wDeck)
{
for(int i=0;i<52;i++)
{
int j=rand()%52;
Card tmp=wDeck[i];
wDeck[i]=wDeck[j];
wDeck[j]=tmp;
}
}
void deal(Card*wDeck)
{
for(int i=0;i<52;i++)
{
cout<<setiosflags(ios::right)
<<setw(5)<<wDeck[i].face<<" of "
<<setiosflags(ios::left)
<<setw(8)<<wDeck[i].suit<<"\t";
if((i+1)%2==0)
cout<<endl;
}
}
#endif
#if 0
/*
* 版本-3
* 使用class封装
*/
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
const int NUM=52;
struct Card{
unsigned face:4;
unsigned suit:2;
unsigned color:1;
};
void fillDeck(Card*);
void deal(Card*);
int main()
{
Card deck[NUM];
fillDeck(deck);
deal(deck);
return 0;
}
void fillDeck(Card *deck)
{
for(int i=0;i<NUM;++i)
{
deck[i].face=i%13;
deck[i].suit=i/13;
deck[i].color=i/26;
}
}
void deal(Card*deck)
{
for(int i=0,j=i+26;i<NUM/2;i++,j++)
{
cout<<"Face:"<<setw(3)<<deck[i].face
<<" Suit:"<<setw(2)<<deck[i].suit
<<" Color:"<<setw(2)<<deck[i].color
<<" "<<"Face:"<<setw(3)<<deck[j].face
<<" Suit:"<<setw(2)<<deck[j].suit
<<" Color:"<<setw(2)<<deck[j].color
<<endl;
}
}
#endif
#if 0
/*
* 19. 十进制转化为十六进制
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print8(char x);
void print16(short x);
void print32(int x);
char hexdigit(int a);
int main(int argc,char*argv[])
{
int digit=32;
if(argc<2) {
printf("Usage:dec2hex number digits\n");
exit(-1);
}
if(argc==2) {
int x=atoi(argv[1]);
print32(x);
}
if(argc>2) {
digit=atoi(argv[2]);
switch(digit) {
case 8: {
char x=atoi(argv[1]);
print8(x);
}
break;
case 16:
{
short x=atoi(argv[1]);
print16(x);
}
break;
default:
{
int x=atoi(argv[1]);
print32(x);
}
break;
}
}
return 0;
}
char hexdigit(int a)
{
static char hexd[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
return hexd[a];
}
void print8(char x)
{
int i;
printf("0x");
for(i=4;i>=0;i-=4)
printf("%c",hexdigit(x>>i&15));
printf("\n");
}
void print16(short x)
{
int i;
printf("0x");
for(i=12;i>=0;i-=4)
printf("%c",hexdigit(x>>i&15));
printf("\n");
}
void print32(int x)
{
int i;
printf("0x");
for(i=28;i>=0;i-=4)
printf("%c",hexdigit(x>>i&15));
printf("\n");
}
#endif
#if 0
/*
* 20. 十进制转化为二进制
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print8(char x);
void print16(short x);
void print32(int x);
int main(int argc,char*argv[])
{
int digit=32;
if(argc<2)
{
printf("Usage:dec2bin number digits\n");
exit(-1);
}
if(argc==2)
{
int x=atoi(argv[1]);
print32(x);
}
if(argc>2)
{
digit=atoi(argv[2]);
switch(digit)
{
case 8:
{
char x=atoi(argv[1]);
print8(x);
}
break;
case 16:
{
short x=atoi(argv[1]);
print16(x);
}
break;
default:
{
int x=atoi(argv[1]);
print32(x);
}
break;
}
}
return 0;
}
void print8(char x)
{
int i;
for(i=7;i>=0;i--)
printf("%d",x>>i&1);
printf("\n");
}
void print16(short x)
{
int i;
for(i=15;i>=0;i--)
printf("%d",x>>i&1);
printf("\n");
}
void print32(int x)
{
int i;
for(i=31;i>=0;i--)
printf("%d",x>>i&1);
printf("\n");
}
#endif
#if 0
/*
* 22. 时间测试
*/
#include <stdio.h>
#include <time.h>
int gcd(int x,int y) {
while(y!=0)
{
int temp=y;
y=x%y;
x=temp;
}
return x;
}
int main() {
clock_t start,finish;
start=clock();
srand((int)time(NULL));
{
int i;
int a,b;
int value;
for(i=0;i<1000000;i++)
{
a=rand()%100000;
b=rand()%100000;
value=gcd(a,b);
// printf("gcd(%d,%d)=%d\n",a,b,value);
}
}
finish=clock();
printf("it took %f seconds to excute\n",((double)(finish-start))/CLOCKS_PER_SEC);
}
#endif
#if 0
/*
* 23. 判断系统是大端还是小端
*/
#include <stdio.h>
int checkSystem()
{
union check
{
int i;
char ch;
}c;
c.i=1;
return (c.ch==1);
}
int checkSystem2()
{
int i=1;
return ((i>>24&&15)==0);
}
int main(int argc,char*argv[])
{
if(checkSystem2())
printf("littleEndian\n");
else
printf("bigEndian\n");
return 0;
}
#endif
/*
* 16. 简单的词典查询
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char *dic[]={
"atlas","A voluem of maps.",
"car","A motorized vechicle.",
"telephone","A communication device.",
"airplane","A flying machine.",
"","",
};
int main()
{
char word[80];
char **p;
do{
puts("Enter the word:");
scanf("%s",word);
p=(char**)dic;
do{
if(!strcmp(*p,word))
{
puts("Meaning:");
puts(*(p+1));
break;
}
p=p+2;
}while(*p);
if(!*p)
puts("Not found.");
puts("Another word?");
scanf("%s",word);
}while(word[0]=='Y'||word[0]=='y');
return 0;
}
#endif
#if 0
/*
* 18. 洗牌程序 版本-1
*/
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::endl;
using std::setw;
using std::ios;
using std::setiosflags;
void shuffle(int [][13]);
void deal(const int[][13],const char*[],const char*[]);
int main()
{
const char* suit[4]={"Hearts","Diamonds","Clubs","Spades"};
const char *face[13]={
"Ace","Deuce","Three","Four","Five",
"Six","Seven","Eight","Nine","Ten",
"Jack","Queen","King",
};
int deck[4][13]={0};
srand((int)time(NULL));
shuffle(deck);
deal(deck,suit,face);
return 0;
}
void shuffle(int deck[][13])
{
for(int i=1;i<=52;i++)
{
int row;
int col;
do
{
row=rand()%4;
col=rand()%13;
}while(deck[row][col]!=0);
deck[row][col]=i;
}
}
void deal(const int deck[][13],const char* suit[],const char* face[])
{
for(int i=1;i<=52;i++)
{
for(int j=0;j<4;j++)
{
for(int k=0;k<13;k++)
if(deck[j][k]==i)
{
cout<<setw(5)<<setiosflags(ios::right)
<<face[k]<<" of "
<<setw(8)<<setiosflags(ios::left)
<<suit[j]
<<(i%2==0?'\n':'\t');
goto L;
}
}
L:
;
}
}
#endif
#if 0
/*
* 版本-2
* 结构体
*/
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::endl;
using std::setw;
using std::ios;
struct Card {
const char *face;
const char *suit;
};
void fillDeck(Card*,const char*[],const char*[]);
void shuffle(Card*);
void deal(Card*);
int main()
{
Card deck[52];
const char* suit[4]={"Hearts","Diamonds","Clubs","Spades"};
const char *face[13]={
"Ace","Deuce","Three","Four","Five",
"Six","Seven","Eight","Nine","Ten",
"Jack","Queen","King",
};
srand(time(0));
fillDeck(deck,face,suit);
shuffle(deck);
deal(deck);
return 0;
}
void fillDeck(Card*wDeck,const char*wFace[],const char*wSuit[])
{
for(int i=0;i<52;i++)
{
wDeck[i].face=wFace[i%13];
wDeck[i].suit=wSuit[i/13];
}
}
void shuffle(Card*wDeck)
{
for(int i=0;i<52;i++)
{
int j=rand()%52;
Card tmp=wDeck[i];
wDeck[i]=wDeck[j];
wDeck[j]=tmp;
}
}
void deal(Card*wDeck)
{
for(int i=0;i<52;i++)
{
cout<<setiosflags(ios::right)
<<setw(5)<<wDeck[i].face<<" of "
<<setiosflags(ios::left)
<<setw(8)<<wDeck[i].suit<<"\t";
if((i+1)%2==0)
cout<<endl;
}
}
#endif
#if 0
/*
* 版本-3
* 使用class封装
*/
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
const int NUM=52;
struct Card{
unsigned face:4;
unsigned suit:2;
unsigned color:1;
};
void fillDeck(Card*);
void deal(Card*);
int main()
{
Card deck[NUM];
fillDeck(deck);
deal(deck);
return 0;
}
void fillDeck(Card *deck)
{
for(int i=0;i<NUM;++i)
{
deck[i].face=i%13;
deck[i].suit=i/13;
deck[i].color=i/26;
}
}
void deal(Card*deck)
{
for(int i=0,j=i+26;i<NUM/2;i++,j++)
{
cout<<"Face:"<<setw(3)<<deck[i].face
<<" Suit:"<<setw(2)<<deck[i].suit
<<" Color:"<<setw(2)<<deck[i].color
<<" "<<"Face:"<<setw(3)<<deck[j].face
<<" Suit:"<<setw(2)<<deck[j].suit
<<" Color:"<<setw(2)<<deck[j].color
<<endl;
}
}
#endif
#if 0
/*
* 19. 十进制转化为十六进制
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print8(char x);
void print16(short x);
void print32(int x);
char hexdigit(int a);
int main(int argc,char*argv[])
{
int digit=32;
if(argc<2) {
printf("Usage:dec2hex number digits\n");
exit(-1);
}
if(argc==2) {
int x=atoi(argv[1]);
print32(x);
}
if(argc>2) {
digit=atoi(argv[2]);
switch(digit) {
case 8: {
char x=atoi(argv[1]);
print8(x);
}
break;
case 16:
{
short x=atoi(argv[1]);
print16(x);
}
break;
default:
{
int x=atoi(argv[1]);
print32(x);
}
break;
}
}
return 0;
}
char hexdigit(int a)
{
static char hexd[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
return hexd[a];
}
void print8(char x)
{
int i;
printf("0x");
for(i=4;i>=0;i-=4)
printf("%c",hexdigit(x>>i&15));
printf("\n");
}
void print16(short x)
{
int i;
printf("0x");
for(i=12;i>=0;i-=4)
printf("%c",hexdigit(x>>i&15));
printf("\n");
}
void print32(int x)
{
int i;
printf("0x");
for(i=28;i>=0;i-=4)
printf("%c",hexdigit(x>>i&15));
printf("\n");
}
#endif
#if 0
/*
* 20. 十进制转化为二进制
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print8(char x);
void print16(short x);
void print32(int x);
int main(int argc,char*argv[])
{
int digit=32;
if(argc<2)
{
printf("Usage:dec2bin number digits\n");
exit(-1);
}
if(argc==2)
{
int x=atoi(argv[1]);
print32(x);
}
if(argc>2)
{
digit=atoi(argv[2]);
switch(digit)
{
case 8:
{
char x=atoi(argv[1]);
print8(x);
}
break;
case 16:
{
short x=atoi(argv[1]);
print16(x);
}
break;
default:
{
int x=atoi(argv[1]);
print32(x);
}
break;
}
}
return 0;
}
void print8(char x)
{
int i;
for(i=7;i>=0;i--)
printf("%d",x>>i&1);
printf("\n");
}
void print16(short x)
{
int i;
for(i=15;i>=0;i--)
printf("%d",x>>i&1);
printf("\n");
}
void print32(int x)
{
int i;
for(i=31;i>=0;i--)
printf("%d",x>>i&1);
printf("\n");
}
#endif
#if 0
/*
* 22. 时间测试
*/
#include <stdio.h>
#include <time.h>
int gcd(int x,int y) {
while(y!=0)
{
int temp=y;
y=x%y;
x=temp;
}
return x;
}
int main() {
clock_t start,finish;
start=clock();
srand((int)time(NULL));
{
int i;
int a,b;
int value;
for(i=0;i<1000000;i++)
{
a=rand()%100000;
b=rand()%100000;
value=gcd(a,b);
// printf("gcd(%d,%d)=%d\n",a,b,value);
}
}
finish=clock();
printf("it took %f seconds to excute\n",((double)(finish-start))/CLOCKS_PER_SEC);
}
#endif
#if 0
/*
* 23. 判断系统是大端还是小端
*/
#include <stdio.h>
int checkSystem()
{
union check
{
int i;
char ch;
}c;
c.i=1;
return (c.ch==1);
}
int checkSystem2()
{
int i=1;
return ((i>>24&&15)==0);
}
int main(int argc,char*argv[])
{
if(checkSystem2())
printf("littleEndian\n");
else
printf("bigEndian\n");
return 0;
}
#endif
5.
#if 0
/*
* 23. 大数乘法
*/
// using vectors to implement the multiplication of two big integers.
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
void multiply(vector<int> &a,vector<int> &b,vector<int> &result)
{
int k;
for(int i=0;i<a.size();++i){
k=i;
for(int j=0;j<b.size();++j){
result[k++]+=a[i]*b[j];
}
}
for(k=result.size()-1;k>=0;--k){
if(result[k]>9){
if(k!=0){
result[k-1]+=result[k]/10;
result[k]%=10;
}
else{
int tmp=result[k]/10;
result[k]%=10;
result.insert(result.begin(),tmp);
}
}
}
}
int main(int argc,char*argv[])
{
if(argc<3){
cout<<"Usage:"<<argv[0]<<" num1 num2"<<endl;
return -1;
}
string s1(argv[1]),s2(argv[2]);
vector<int> a,b;
a.reserve(s1.size());
b.reserve(s2.size());
for(int i=0;i<s1.size();++i){
a.push_back(s1[i]-'0');
}
for(int i=0;i<s2.size();++i){
b.push_back(s2[i]-'0');
}
vector<int>c(a.size()+b.size()-1,0);
multiply(a,b,c);
for(int i=0;i<c.size();++i)
cout<<c[i];
cout<<endl;
return 0;
}
测试脚本:
#!/bin/bash
limit=10000
for(( i=0;i<100;++i))
do
a=`echo $(($RANDOM%$limit))`
b=`echo $(($RANDOM%$limit))`
r1=`expr $a \* $b`
r2=`./big_int_multiply $a $b`
echo -ne "a=$a\tb=$b\tr1=$r1\tr2=$r2\t"
if [ $r1 -eq $r2 ]
then
echo "ok"
else
echo "ohh,bad"
fi
done
#endif
#if 0
大数乘法的类
#include <deque>
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using std::deque;
using std::vector;
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::ostream;
using std::istream;
class DividedByZeroException{};
class BigInteger{
public:
BigInteger(int);
BigInteger(string&);
BigInteger();
BigInteger(const BigInteger&);
BigInteger& operator=(const BigInteger& rhs);
BigInteger& operator++();
BigInteger operator++(int);
BigInteger& operator--();
BigInteger operator--(int);
BigInteger& operator+=(const BigInteger&);
BigInteger& operator-=(const BigInteger&);
BigInteger& operator*=(const BigInteger&);
BigInteger& operator/=(const BigInteger&)throw(DividedByZeroException);
BigInteger& operator%=(const BigInteger&)throw(DividedByZeroException);
friend BigInteger operator-(const BigInteger&);
friend BigInteger operator+(const BigInteger&, const BigInteger&);
friend BigInteger operator-(const BigInteger&, const BigInteger&);
friend BigInteger operator*(const BigInteger&, const BigInteger&);
friend BigInteger operator/(const BigInteger&, const BigInteger&)throw(DividedByZeroException);
friend BigInteger operator%(const BigInteger&, const BigInteger&)throw(DividedByZeroException);
friend bool operator>(const BigInteger&, const BigInteger&);
friend bool operator<(const BigInteger&, const BigInteger&);
friend bool operator==(const BigInteger&, const BigInteger&);
friend bool operator!=(const BigInteger&, const BigInteger&);
friend bool operator>=(const BigInteger&, const BigInteger&);
friend bool operator<=(const BigInteger&, const BigInteger&);
friend BigInteger abs(const BigInteger&);
friend BigInteger pow(const BigInteger&, int);
friend ostream& operator<<(ostream&,const BigInteger&);
friend istream& operator>>(istream&, BigInteger&);
private:
void trim();
//positive operation
void add(const vector<char>&);
void substract(const vector<char>&);
void multiply(const vector<char>&);
void devide(const vector<char>&);
void mod(const vector<char>&);
bool g_than(const vector<char>&)const;
bool g_equal(const vector<char>&)const;
bool equal(const vector<char>&)const;
public:
static const BigInteger ZERO;
static const BigInteger ONE;
static const BigInteger TEN;
private:
vector<char> digits;
bool sign;
};
const BigInteger BigInteger::ZERO=BigInteger(0);
const BigInteger BigInteger::ONE=BigInteger(1);
const BigInteger BigInteger::TEN=BigInteger(10);
BigInteger::BigInteger():sign(true){ }
BigInteger::BigInteger(int val){
if(val>=0)
sign=true;
else
{
sign=false;
val*=-1;
}
do{
digits.push_back((char)val%10);
val/=10;
}while(val!=0);
}
BigInteger::BigInteger(string& def){
sign=true;
for(string::reverse_iterator iter=def.rbegin();iter!=def.rend();++iter){
char ch(*iter);
cout<<"ch:"<<ch<<endl;
if(iter==def.rend()-1){
if(ch=='+')
break;
if(ch=='-')
{
sign=false;
break;
}
}
digits.push_back(ch-'0');
}
trim();
}
void BigInteger::trim(){
vector<char>::reverse_iterator iter=digits.rbegin();
while(!digits.empty()&&(*iter)==0){
digits.pop_back();
iter=digits.rbegin();
}
if(digits.size()==0){
sign=true;
digits.push_back(0);
}
}
BigInteger::BigInteger(const BigInteger& rhs):sign(rhs.sign),digits(rhs.digits){}
BigInteger& BigInteger::operator=(const BigInteger& rhs){
if(this!=&rhs){
sign=rhs.sign;
digits=rhs.digits;
}
return *this;
}
BigInteger abs(const BigInteger& rhs){
BigInteger res(rhs);
res.sign=true;
return res;
}
BigInteger pow(const BigInteger& rhs,int a){
BigInteger res(1);
for(int i=0;i<a;++i){
res*=rhs;
}
return res;
}
bool BigInteger::g_than(const vector<char>&rhs)const{
if(digits.size()>rhs.size())
return true;
else if(digits.size()<rhs.size())
return false;
else{
vector<char>::const_reverse_iterator iter1;
vector<char>::const_reverse_iterator iter2;
iter1=digits.rbegin();
iter2=rhs.rbegin();
while(iter1!=digits.rend()){
if(*iter1>*iter2)
return true;
else if(*iter1<*iter2)
return false;
else{
++iter1;
++iter2;
}
}
return false;
}
}
bool BigInteger::g_equal(const vector<char>&rhs)const{
if(digits.size()>rhs.size())
return true;
else if(digits.size()<rhs.size())
return false;
else{
vector<char>::const_reverse_iterator iter1;
vector<char>::const_reverse_iterator iter2;
iter1=digits.rbegin();
iter2=rhs.rbegin();
while(iter1!=digits.rend()){
if(*iter1>*iter2)
return true;
else if(*iter1<*iter2)
return false;
else{
++iter1;
++iter2;
}
}
return true;
}
}
bool BigInteger::equal(const vector<char>& rhs)const{
if(digits.size()!=rhs.size())
return false;
else{
vector<char>::const_reverse_iterator iter1;
vector<char>::const_reverse_iterator iter2;
iter1=digits.rbegin();
iter2=rhs.rbegin();
while(iter1!=digits.rend()){
if(*iter1!=*iter2)
return false;
else{
++iter1;
++iter2;
}
}
return true;
}
}
void BigInteger::add(const vector<char>& rhs){
vector<char>::iterator iter1;
vector<char>::const_iterator iter2;
iter1=digits.begin();
iter2=rhs.begin();
char carry=0;
while(iter1!=digits.end()&&iter2!=rhs.end()){
*iter1+=(*iter2+carry);
carry=(*iter1>9);
*iter1%=10;
++iter1;
++iter2;
}
while(iter1!=digits.end()){
(*iter1)+=carry;
carry=(*iter1>9);
*iter1%=10;
++iter1;
}
while(iter2!=rhs.end()){
char val=(*iter2)+carry;
carry=(val>9);
val%=10;
digits.push_back(val);
++iter2;
}
if(carry!=0)
digits.push_back(carry);
}
void BigInteger::substract(const vector<char>& rhs){
vector<char>::iterator iter1;
vector<char>::const_iterator iter2;
iter1=digits.begin();
iter2=rhs.begin();
char borrow=0;
while(iter1!=digits.end()&&iter2!=rhs.end()){
*iter1-=(*iter2+borrow);
if(*iter1<0){
borrow=1;
*iter1+=10;
}
++iter1;
++iter2;
}
while(iter1!=digits.end()){
(*iter1)-=borrow;
if(*iter1<0){
borrow=1;
*iter1+=10;
}
else
break;
++iter1;
}
}
void BigInteger::multiply(const vector<char>& rhs){
vector<char> res(digits.size()+rhs.size()-1,0);
vector<char>::iterator k;
vector<char>::iterator iter1;
vector<char>::const_iterator iter2;
for(iter1=digits.begin();iter1!=digits.end();++iter1){
k=res.begin()+(iter1-digits.begin());
for(iter2=rhs.begin();iter2!=rhs.end();++iter2,++k){
*k+=(*iter1)*(*iter2);
}
}
for(k=res.begin();k!=res.end();++k){
if(*k>9){
if(k!=res.end()-1){
*(k++)=*k/10;
*k%=10;
}
else{
char val=*k/10;
*k%=10;
res.push_back(val);
break;
}
}
}
digits=res;
}
BigInteger& BigInteger::operator+=(const BigInteger& rhs){
if(sign==rhs.sign)
add(rhs.digits);
else{
if(g_equal(rhs.digits)){
substract(rhs.digits);
}
else{
vector<char> tmp(digits);
digits=rhs.digits;
substract(tmp);
sign=rhs.sign;
}
trim();
}
return *this;
}
BigInteger& BigInteger::operator-=(const BigInteger& rhs){
if(sign==rhs.sign){
if(sign){
if(g_equal(rhs.digits)){
substract(rhs.digits);
}
else{
vector<char> tmp(digits);
digits=rhs.digits;
substract(tmp);
sign=false;
}
}
else{
if(g_equal(rhs.digits)){
substract(rhs.digits);
sign=false;
}
else{
vector<char> tmp(digits);
digits=rhs.digits;
substract(tmp);
sign=true;
}
}
}
else{
add(rhs.digits);
}
trim();
return *this;
}
BigInteger& BigInteger::operator*=(const BigInteger& rhs){
multiply(rhs.digits);
sign=(sign==rhs.sign);
return *this;
}
BigInteger& BigInteger::operator++(){
*this+=(ONE);
return *this;
}
BigInteger BigInteger::operator++(int){
BigInteger res=*this;
*this+=(ONE);
return res;
}
BigInteger& BigInteger::operator--(){
*this-=(ONE);
return *this;
}
BigInteger BigInteger::operator--(int){
BigInteger res=*this;
*this-=(ONE);
return res;
}
BigInteger operator-(const BigInteger& rhs){
BigInteger res;
res.sign=rhs.sign?false:true;
res.digits=rhs.digits;
return res;
}
BigInteger operator+(const BigInteger& rhs1,const BigInteger& rhs2){
BigInteger res(rhs1);
res+=rhs2;
return res;
}
BigInteger operator-(const BigInteger& rhs1,const BigInteger& rhs2){
BigInteger res(rhs1);
res-=rhs2;
return res;
}
BigInteger operator*(const BigInteger& rhs1,const BigInteger& rhs2){
BigInteger res(rhs1);
res*=rhs2;
return res;
}
bool operator>(const BigInteger& rhs1,const BigInteger& rhs2){
if(rhs1.sign==rhs2.sign){
if(rhs1.sign)
return rhs1.g_than(rhs2.digits);
else
return !rhs1.g_than(rhs2.digits);
}
else
{
return rhs1.sign;
}
}
bool operator<(const BigInteger& rhs1,const BigInteger& rhs2){
return !(rhs1>rhs2||rhs1==rhs2);
}
bool operator==(const BigInteger& rhs1,const BigInteger& rhs2){
if(rhs1.sign==rhs2.sign){
return rhs1.equal(rhs2.digits);
}
else
return false;
}
bool operator!=(const BigInteger& rhs1,const BigInteger& rhs2){
return !(rhs1==rhs2);
}
bool operator>=(const BigInteger& rhs1,const BigInteger& rhs2){
return (rhs1>rhs2||rhs1==rhs2);
}
bool operator<=(const BigInteger& rhs1,const BigInteger& rhs2){
return (rhs1<rhs2||rhs1==rhs2);
}
ostream& operator<<(ostream& os,const BigInteger& rhs){
if(!rhs.sign)
os<<"-";
for(vector<char>::const_reverse_iterator iter=rhs.digits.rbegin();iter!=rhs.digits.rend();++iter){
os<<(char)(*iter+'0');
}
return os;
}
istream& operator>>(istream& is,BigInteger& rhs){
string str;
is>>str;
cout<<"str="<<str<<endl;
rhs=BigInteger(str);
return is;
}
int main(){
int n=1;
for(int i=0;i<n;++i){
BigInteger A;
BigInteger B(78);
// BigInteger C=888;
cin>>A;
cout<<"A:"<<A<<" B:"<<B<<endl;
cout<<"A+B:"<<A+B<<endl;
cout<<"A-B:"<<A-B<<endl;
cout<<"A*B:"<<A*B<<endl;
cout<<"pow(A,5):"<<pow(A,5)<<endl;
A++;
cout<<"A++:"<<A<<endl;
++A;
cout<<"++A:"<<A<<endl;
A--;
cout<<"A--:"<<A<<endl;
--A;
cout<<"--A:"<<A<<endl;
A+=B;
cout<<"A+=B:"<<A<<endl;
A-=B;
cout<<"A-=B:"<<A<<endl;
A*=B;
cout<<"A*=B:"<<A<<endl;
}
}
#endif
#if 1
/*
* 24. 背景色的设置
*/
#include <stdio.h>
#include <stdlib.h>
const char *color[]={ "\033[0;40;31m","\033[0;40;32m","\033[0;40;33m","\033[0;40;34m","\033[0;40;35m","\033[0;40;36m"};
const char *const normal = "\033[0m";
int main(){
int n=10;
int i;
for(i=0;i<n;i++)
{
int val=rand()%1000;
int ci=rand()%6;
printf("%s%d%s ",color[ci],val,normal);
}
printf("\n");
}
#endif
/*
* 23. 大数乘法
*/
// using vectors to implement the multiplication of two big integers.
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
void multiply(vector<int> &a,vector<int> &b,vector<int> &result)
{
int k;
for(int i=0;i<a.size();++i){
k=i;
for(int j=0;j<b.size();++j){
result[k++]+=a[i]*b[j];
}
}
for(k=result.size()-1;k>=0;--k){
if(result[k]>9){
if(k!=0){
result[k-1]+=result[k]/10;
result[k]%=10;
}
else{
int tmp=result[k]/10;
result[k]%=10;
result.insert(result.begin(),tmp);
}
}
}
}
int main(int argc,char*argv[])
{
if(argc<3){
cout<<"Usage:"<<argv[0]<<" num1 num2"<<endl;
return -1;
}
string s1(argv[1]),s2(argv[2]);
vector<int> a,b;
a.reserve(s1.size());
b.reserve(s2.size());
for(int i=0;i<s1.size();++i){
a.push_back(s1[i]-'0');
}
for(int i=0;i<s2.size();++i){
b.push_back(s2[i]-'0');
}
vector<int>c(a.size()+b.size()-1,0);
multiply(a,b,c);
for(int i=0;i<c.size();++i)
cout<<c[i];
cout<<endl;
return 0;
}
测试脚本:
#!/bin/bash
limit=10000
for(( i=0;i<100;++i))
do
a=`echo $(($RANDOM%$limit))`
b=`echo $(($RANDOM%$limit))`
r1=`expr $a \* $b`
r2=`./big_int_multiply $a $b`
echo -ne "a=$a\tb=$b\tr1=$r1\tr2=$r2\t"
if [ $r1 -eq $r2 ]
then
echo "ok"
else
echo "ohh,bad"
fi
done
#endif
#if 0
大数乘法的类
#include <deque>
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using std::deque;
using std::vector;
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::ostream;
using std::istream;
class DividedByZeroException{};
class BigInteger{
public:
BigInteger(int);
BigInteger(string&);
BigInteger();
BigInteger(const BigInteger&);
BigInteger& operator=(const BigInteger& rhs);
BigInteger& operator++();
BigInteger operator++(int);
BigInteger& operator--();
BigInteger operator--(int);
BigInteger& operator+=(const BigInteger&);
BigInteger& operator-=(const BigInteger&);
BigInteger& operator*=(const BigInteger&);
BigInteger& operator/=(const BigInteger&)throw(DividedByZeroException);
BigInteger& operator%=(const BigInteger&)throw(DividedByZeroException);
friend BigInteger operator-(const BigInteger&);
friend BigInteger operator+(const BigInteger&, const BigInteger&);
friend BigInteger operator-(const BigInteger&, const BigInteger&);
friend BigInteger operator*(const BigInteger&, const BigInteger&);
friend BigInteger operator/(const BigInteger&, const BigInteger&)throw(DividedByZeroException);
friend BigInteger operator%(const BigInteger&, const BigInteger&)throw(DividedByZeroException);
friend bool operator>(const BigInteger&, const BigInteger&);
friend bool operator<(const BigInteger&, const BigInteger&);
friend bool operator==(const BigInteger&, const BigInteger&);
friend bool operator!=(const BigInteger&, const BigInteger&);
friend bool operator>=(const BigInteger&, const BigInteger&);
friend bool operator<=(const BigInteger&, const BigInteger&);
friend BigInteger abs(const BigInteger&);
friend BigInteger pow(const BigInteger&, int);
friend ostream& operator<<(ostream&,const BigInteger&);
friend istream& operator>>(istream&, BigInteger&);
private:
void trim();
//positive operation
void add(const vector<char>&);
void substract(const vector<char>&);
void multiply(const vector<char>&);
void devide(const vector<char>&);
void mod(const vector<char>&);
bool g_than(const vector<char>&)const;
bool g_equal(const vector<char>&)const;
bool equal(const vector<char>&)const;
public:
static const BigInteger ZERO;
static const BigInteger ONE;
static const BigInteger TEN;
private:
vector<char> digits;
bool sign;
};
const BigInteger BigInteger::ZERO=BigInteger(0);
const BigInteger BigInteger::ONE=BigInteger(1);
const BigInteger BigInteger::TEN=BigInteger(10);
BigInteger::BigInteger():sign(true){ }
BigInteger::BigInteger(int val){
if(val>=0)
sign=true;
else
{
sign=false;
val*=-1;
}
do{
digits.push_back((char)val%10);
val/=10;
}while(val!=0);
}
BigInteger::BigInteger(string& def){
sign=true;
for(string::reverse_iterator iter=def.rbegin();iter!=def.rend();++iter){
char ch(*iter);
cout<<"ch:"<<ch<<endl;
if(iter==def.rend()-1){
if(ch=='+')
break;
if(ch=='-')
{
sign=false;
break;
}
}
digits.push_back(ch-'0');
}
trim();
}
void BigInteger::trim(){
vector<char>::reverse_iterator iter=digits.rbegin();
while(!digits.empty()&&(*iter)==0){
digits.pop_back();
iter=digits.rbegin();
}
if(digits.size()==0){
sign=true;
digits.push_back(0);
}
}
BigInteger::BigInteger(const BigInteger& rhs):sign(rhs.sign),digits(rhs.digits){}
BigInteger& BigInteger::operator=(const BigInteger& rhs){
if(this!=&rhs){
sign=rhs.sign;
digits=rhs.digits;
}
return *this;
}
BigInteger abs(const BigInteger& rhs){
BigInteger res(rhs);
res.sign=true;
return res;
}
BigInteger pow(const BigInteger& rhs,int a){
BigInteger res(1);
for(int i=0;i<a;++i){
res*=rhs;
}
return res;
}
bool BigInteger::g_than(const vector<char>&rhs)const{
if(digits.size()>rhs.size())
return true;
else if(digits.size()<rhs.size())
return false;
else{
vector<char>::const_reverse_iterator iter1;
vector<char>::const_reverse_iterator iter2;
iter1=digits.rbegin();
iter2=rhs.rbegin();
while(iter1!=digits.rend()){
if(*iter1>*iter2)
return true;
else if(*iter1<*iter2)
return false;
else{
++iter1;
++iter2;
}
}
return false;
}
}
bool BigInteger::g_equal(const vector<char>&rhs)const{
if(digits.size()>rhs.size())
return true;
else if(digits.size()<rhs.size())
return false;
else{
vector<char>::const_reverse_iterator iter1;
vector<char>::const_reverse_iterator iter2;
iter1=digits.rbegin();
iter2=rhs.rbegin();
while(iter1!=digits.rend()){
if(*iter1>*iter2)
return true;
else if(*iter1<*iter2)
return false;
else{
++iter1;
++iter2;
}
}
return true;
}
}
bool BigInteger::equal(const vector<char>& rhs)const{
if(digits.size()!=rhs.size())
return false;
else{
vector<char>::const_reverse_iterator iter1;
vector<char>::const_reverse_iterator iter2;
iter1=digits.rbegin();
iter2=rhs.rbegin();
while(iter1!=digits.rend()){
if(*iter1!=*iter2)
return false;
else{
++iter1;
++iter2;
}
}
return true;
}
}
void BigInteger::add(const vector<char>& rhs){
vector<char>::iterator iter1;
vector<char>::const_iterator iter2;
iter1=digits.begin();
iter2=rhs.begin();
char carry=0;
while(iter1!=digits.end()&&iter2!=rhs.end()){
*iter1+=(*iter2+carry);
carry=(*iter1>9);
*iter1%=10;
++iter1;
++iter2;
}
while(iter1!=digits.end()){
(*iter1)+=carry;
carry=(*iter1>9);
*iter1%=10;
++iter1;
}
while(iter2!=rhs.end()){
char val=(*iter2)+carry;
carry=(val>9);
val%=10;
digits.push_back(val);
++iter2;
}
if(carry!=0)
digits.push_back(carry);
}
void BigInteger::substract(const vector<char>& rhs){
vector<char>::iterator iter1;
vector<char>::const_iterator iter2;
iter1=digits.begin();
iter2=rhs.begin();
char borrow=0;
while(iter1!=digits.end()&&iter2!=rhs.end()){
*iter1-=(*iter2+borrow);
if(*iter1<0){
borrow=1;
*iter1+=10;
}
++iter1;
++iter2;
}
while(iter1!=digits.end()){
(*iter1)-=borrow;
if(*iter1<0){
borrow=1;
*iter1+=10;
}
else
break;
++iter1;
}
}
void BigInteger::multiply(const vector<char>& rhs){
vector<char> res(digits.size()+rhs.size()-1,0);
vector<char>::iterator k;
vector<char>::iterator iter1;
vector<char>::const_iterator iter2;
for(iter1=digits.begin();iter1!=digits.end();++iter1){
k=res.begin()+(iter1-digits.begin());
for(iter2=rhs.begin();iter2!=rhs.end();++iter2,++k){
*k+=(*iter1)*(*iter2);
}
}
for(k=res.begin();k!=res.end();++k){
if(*k>9){
if(k!=res.end()-1){
*(k++)=*k/10;
*k%=10;
}
else{
char val=*k/10;
*k%=10;
res.push_back(val);
break;
}
}
}
digits=res;
}
BigInteger& BigInteger::operator+=(const BigInteger& rhs){
if(sign==rhs.sign)
add(rhs.digits);
else{
if(g_equal(rhs.digits)){
substract(rhs.digits);
}
else{
vector<char> tmp(digits);
digits=rhs.digits;
substract(tmp);
sign=rhs.sign;
}
trim();
}
return *this;
}
BigInteger& BigInteger::operator-=(const BigInteger& rhs){
if(sign==rhs.sign){
if(sign){
if(g_equal(rhs.digits)){
substract(rhs.digits);
}
else{
vector<char> tmp(digits);
digits=rhs.digits;
substract(tmp);
sign=false;
}
}
else{
if(g_equal(rhs.digits)){
substract(rhs.digits);
sign=false;
}
else{
vector<char> tmp(digits);
digits=rhs.digits;
substract(tmp);
sign=true;
}
}
}
else{
add(rhs.digits);
}
trim();
return *this;
}
BigInteger& BigInteger::operator*=(const BigInteger& rhs){
multiply(rhs.digits);
sign=(sign==rhs.sign);
return *this;
}
BigInteger& BigInteger::operator++(){
*this+=(ONE);
return *this;
}
BigInteger BigInteger::operator++(int){
BigInteger res=*this;
*this+=(ONE);
return res;
}
BigInteger& BigInteger::operator--(){
*this-=(ONE);
return *this;
}
BigInteger BigInteger::operator--(int){
BigInteger res=*this;
*this-=(ONE);
return res;
}
BigInteger operator-(const BigInteger& rhs){
BigInteger res;
res.sign=rhs.sign?false:true;
res.digits=rhs.digits;
return res;
}
BigInteger operator+(const BigInteger& rhs1,const BigInteger& rhs2){
BigInteger res(rhs1);
res+=rhs2;
return res;
}
BigInteger operator-(const BigInteger& rhs1,const BigInteger& rhs2){
BigInteger res(rhs1);
res-=rhs2;
return res;
}
BigInteger operator*(const BigInteger& rhs1,const BigInteger& rhs2){
BigInteger res(rhs1);
res*=rhs2;
return res;
}
bool operator>(const BigInteger& rhs1,const BigInteger& rhs2){
if(rhs1.sign==rhs2.sign){
if(rhs1.sign)
return rhs1.g_than(rhs2.digits);
else
return !rhs1.g_than(rhs2.digits);
}
else
{
return rhs1.sign;
}
}
bool operator<(const BigInteger& rhs1,const BigInteger& rhs2){
return !(rhs1>rhs2||rhs1==rhs2);
}
bool operator==(const BigInteger& rhs1,const BigInteger& rhs2){
if(rhs1.sign==rhs2.sign){
return rhs1.equal(rhs2.digits);
}
else
return false;
}
bool operator!=(const BigInteger& rhs1,const BigInteger& rhs2){
return !(rhs1==rhs2);
}
bool operator>=(const BigInteger& rhs1,const BigInteger& rhs2){
return (rhs1>rhs2||rhs1==rhs2);
}
bool operator<=(const BigInteger& rhs1,const BigInteger& rhs2){
return (rhs1<rhs2||rhs1==rhs2);
}
ostream& operator<<(ostream& os,const BigInteger& rhs){
if(!rhs.sign)
os<<"-";
for(vector<char>::const_reverse_iterator iter=rhs.digits.rbegin();iter!=rhs.digits.rend();++iter){
os<<(char)(*iter+'0');
}
return os;
}
istream& operator>>(istream& is,BigInteger& rhs){
string str;
is>>str;
cout<<"str="<<str<<endl;
rhs=BigInteger(str);
return is;
}
int main(){
int n=1;
for(int i=0;i<n;++i){
BigInteger A;
BigInteger B(78);
// BigInteger C=888;
cin>>A;
cout<<"A:"<<A<<" B:"<<B<<endl;
cout<<"A+B:"<<A+B<<endl;
cout<<"A-B:"<<A-B<<endl;
cout<<"A*B:"<<A*B<<endl;
cout<<"pow(A,5):"<<pow(A,5)<<endl;
A++;
cout<<"A++:"<<A<<endl;
++A;
cout<<"++A:"<<A<<endl;
A--;
cout<<"A--:"<<A<<endl;
--A;
cout<<"--A:"<<A<<endl;
A+=B;
cout<<"A+=B:"<<A<<endl;
A-=B;
cout<<"A-=B:"<<A<<endl;
A*=B;
cout<<"A*=B:"<<A<<endl;
}
}
#endif
#if 1
/*
* 24. 背景色的设置
*/
#include <stdio.h>
#include <stdlib.h>
const char *color[]={ "\033[0;40;31m","\033[0;40;32m","\033[0;40;33m","\033[0;40;34m","\033[0;40;35m","\033[0;40;36m"};
const char *const normal = "\033[0m";
int main(){
int n=10;
int i;
for(i=0;i<n;i++)
{
int val=rand()%1000;
int ci=rand()%6;
printf("%s%d%s ",color[ci],val,normal);
}
printf("\n");
}
#endif