标签:
结对编程
结对人:宫成荣
代码如下:
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 struct Word /* 单词对象 */ 6 { 7 Word() : Str( "" ), Count( 0 ) 8 { 9 } 10 string Str; 11 int Count; 12 }; 13 14 15 void CalcCount( Word *words, string &content, int size ) /* 统计词频 */ 16 { 17 int i; /* words单词 content内容 size个数 */ 18 for ( i = 0; i < size; i++ ) 19 { 20 if ( words[i].Str == content ) 21 { 22 words[i].Count++; 23 return; 24 }else if ( words[i].Str == "" ) 25 break; 26 } 27 words[i].Str = content; 28 words[i].Count = 1; 29 } 30 31 32 int main() 33 { 34 char ch; 35 Word *words; 36 string content; 37 cout << "输入一段英文:"; 38 getline( cin, content ); 39 while ( cin.get( ch ) ) /* 把所有小写字母换成大写字母 */ 40 { 41 ch = cin.get(); /* 此部分存疑,可能是输入问题,这一部分无法实现 */ 42 if ( 97 <= ch && ch <= 122 ) 43 { 44 char (ch) = char(ch - 32); 45 break; 46 } 47 } 48 49 int wCount = 1; /* 计算单词总数 */ 50 if ( content.length() < 4 ) /* 长度小于4的单词删除 */ 51 { 52 wCount--; 53 content.erase( 0, offset + 1 ); 54 offset = content.find( ‘ ‘ ); 55 continue; 56 } 57 for ( unsigned int i = 0; i < content.length(); i++ ) 58 { 59 if ( content[i] == ‘ ‘ || content[i] == ‘\t‘ || content[i] == ‘\n‘ || content[i] == ‘.‘ || content[i] == ‘,‘ ) 60 wCount++; /* 分隔符分为‘ ‘,‘\t‘,‘\n‘,‘,‘,‘.‘五种 */ 61 } 62 words = new Word[wCount]; 63 64 string::size_type offset = content.find( ‘ ‘ || ‘\t‘ || ‘\n‘ || ‘.‘ || ‘,‘ ); /* 单词以分隔符隔开 */ 65 while ( offset != string::npos ) 66 { 67 string wStr = content.substr( 0, offset ); 68 content.erase( 0, offset + 1 ); 69 CalcCount( words, wStr, wCount ); 70 offset = content.find( ‘ ‘ || ‘\t‘ || ‘\n‘ || ‘.‘ || ‘,‘ ); 71 } 72 CalcCount( words, content, wCount ); 73 74 for ( int j = 0; j < wCount; j++ ) /* 最后输出结果 */ 75 { 76 cout << words[j].Str << ":" << words[j].Count << endl; 77 } 78 delete[] words; 79 return(0); 80 }
后缀表达式的转换:
1 //计算后缀表达式 2 void calculate(deque<char>& coll3, stack<int>& coll4) 3 { 4 while(!coll3.empty()) 5 { 6 char c = coll3.front(); 7 coll3.pop_front(); 8 9 //如果是操作数,压入栈中 10 if(c>=‘0‘&&c<=‘9‘) 11 { 12 //减去‘0‘得出偏移值,即为真实数值(如果直接转换成int,结果不对,因为char 转换为int是其编码值,例如‘1‘的编码值为49 13 int op = c-‘0‘; 14 coll4.push(op); 15 } 16 else //如果是操作符,从栈中弹出元素进行计算 17 { 18 int op1 = coll4.top(); 19 coll4.pop(); 20 int op2 = coll4.top(); 21 coll4.pop(); 22 switch(c) 23 { 24 case ‘+‘: 25 coll4.push(op2+op1); 26 break; 27 case ‘-‘: 28 coll4.push(op2-op1); 29 break; 30 case ‘*‘: 31 coll4.push(op2*op1); 32 break; 33 case ‘/‘: 34 coll4.push(op2/op1); //注意是op2(op)op1而不是op1(op)op2 35 break; 36 } 37 } 38 } 39 }
单元测试代码
1 /* tcut.h: Tiny C Unit Test framework*/ 2 #ifndef _TCUT_H 3 #define _TCUT_H 4 5 #define tcut_assert(what, test) do { if (!(test)) return what; } while (0) 6 #define tcut_run_test(test) do { char *what = test(); nr_tests++; if (what) return what; } while (0) 7 extern int nr_tests; 8 9 #endif
结果
标签:
原文地址:http://www.cnblogs.com/brilliant2016/p/5917833.html