4.2

来源:互联网 发布:网络恐怖主义论文 编辑:程序博客网 时间:2024/05/06 12:03

/*
 *编写程序定义一个vector对象,其每个元素都是指向string类型的指针,
 *读取该vector对象,输出每个string的内容及其相应的长度。
 */

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
 vector<string *> strvec;
 string str1;
 string *strp;

 while(cin >> str1)
 { 
  string *strp = new string; //必须为指针分配内存
  *strp = str1;
  strvec.push_back( strp++ );
 }

 for(vector<string *>::iterator iter = strvec.begin(); iter != strvec.end(); ++iter)
 {
  cout<< **iter <<' '<< (**iter).size() << ' ';
 }
 
 for(vector<string *>::iterator iter = strvec.begin(); iter != strvec.end(); ++iter)
 {
  delete *iter;
 }

 system("pause");
 return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

#include <iostream>

using namespace std;

int main()
{
 char ch;
 int acnt = 0,ecnt = 0,ocnt = 0,ucnt = 0,icnt = 0;
 int spacecnt = 0,tablecnt =0,newlinecnt = 0;
 while (cin.get(ch)) //不能用cin >> ch,因为它不能读空格,制表,和回车
 {
  switch(ch)
  {
  case 'a':
   ++acnt;
   break;
  case 'e':
   ++ecnt;
   break;
  case ' ':
   ++spacecnt;
   break;
  case '\t':
   ++tablecnt;
   break;
  case '\n':
   ++newlinecnt;
   break;

  }
 }

 cout << acnt << ' ' << ecnt << ' '<< spacecnt << ' '<< tablecnt << ' '<< newlinecnt;

 system("pause");
 return 0;
}

 

 

 

 


/*
 *编写一个小程序,从标准输入读入一系列string对象,寻找连续重复出现的单词。程序应该找出满足以下条件的单词的输入位置:
 *该单词的后面紧跟着再次出现自己本身。跟踪重复次数最多的单词及其重复次数。
 *输出重复次数的最大值,若没有单词重复则输出说明信息。例如:如果输入是:
 *how,now now now brown cow cow
 *则输出表明now单词出现三次
 */

#include <iostream>
#include <string>

using namespace std;

int main()
{
 string pre_str, cur_str, max_str;
 int max_int = 1, current_int = 0;

 while(cin >> cur_str)
 {
  if(pre_str == cur_str)
  {
   current_int ++;
   max_int = current_int > max_int ? current_int : max_int;
   max_str = cur_str;
  }
  else
  {
   current_int = 1;

   pre_str = cur_str;
  }

 }

 cout << max_int << max_str;


 system("pause");
 return 0;
}

 

 

 

 

 

 

 

 


/*
 *修改6.11节习题所编写的程序,使其可以有条件地输出运行时的信息。例如:可以输出每一个读入的单词,用来判断循环是否正确
 *地找到第一个连续出现的大写字母开头的单词。分别在打开和关闭调试的情况下变异和运行这个程序。
 *
 *结果为:在打开调试器的情况下(即定义DEBUG)编译和运行改程序,会输出所读入的每个单词;
 *如果在关闭调试起的情况下(即定义NDEBUG)编译和运行改程序,则不会输出所读入的每个单词。
 */

#include <iostream>
#include <string>


using namespace std;

int main()
{
 string pre_str, cur_str, max_str;
 int max_int = 1, current_int = 0;

 while(cin >> cur_str)
 {
  #ifndef NDEBUG
  cout << cur_str <<endl;
  #endif


  if(cur_str[0] >= 'A' && cur_str[0] <= 'Z'){
  if(pre_str == cur_str)
  {
   max_str = cur_str;
   cout << pre_str;
   break;
  }
  else
  {
   pre_str = cur_str;
  }}
  else
   continue;

 }

 

 system("pause");
 return 0;
}

 

 

原创粉丝点击