[C++]实验一:使用VC++6.0环境编写C++程序

时间:2022-09-08 08:22:02

// Expm1.1
// Write a non-graphic standard C++ program:

#include <iostream>
void main(void)
{
    std::cout<<"Hello!/n";
    std::cout<<"Welcome to c++!/n";
}

// 清翔兔

/*
2. Write a program that counts and prints the number of lines, words, and letter frequencies in its input.  For example, the input:
Two roads diverged in a yellow wood,
And sorry I would not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;
Would produce the output:
The input had 5 lines, 37 words, and the following letter frequencies:
   A:10   B:3   C:2   D:13   E:15    F:1  ……
*/

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

void main()
{
 string word;
 char p;
 int line=1; //调整行数计算误差
 int words=0;
 map< char ,int ,less<char> > letters;
 while ( cin >> word )
 {
  words++;  //单词数加一
  for ( int i=0 ; i < word.size() ; i++ ) //单个单词内部循环
  {
   if (( word[i] >= 65 && word[i] <= 90) ||
    ( word[i] >=97 && word[i] <= 122) )  //过滤标点符号
   {
   if ( word[i] >= 97) word[i] -= 32;  //大小写合并
   letters[word[i]]++;   //字母数加一
   }
  }
  // 判断行数
  cin.get(p);
  if (p=='/n') line++;
}
 cout << "The input had " << line << " lines,"
   << words << " words,"
      << "The frequencies of words:" << endl;
 for ( map< char ,int,less<char> >::iterator iter = letters.begin(); iter!= letters.end() ; iter++ )
 cout << iter->first << ":" << iter->second << "/t";
}

// 清翔兔

/*
3. Modify your program from problem 1
so that it counts the frequencies of words instead of letters.
*/

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

void main()
{
 string word;
 map< string ,int ,less<string> > words;
 string filter = ",. :'";    // 要去除的标点
 while ( cin >> word) 
 {
  // 去标点处理
  string::size_type pos = 0;
  while (( pos = word.find_first_of ( filter ,pos ))!= string::npos)
   word.erase( pos ,1);
  words[word]++; //加入map
 }
 cout << "The frequencies of words:" << endl;
 for ( map< string ,int,less<string> >::iterator iter = words.begin(); iter!= words.end() ; iter++ )
 cout << iter->first << ":" << iter->second << "/t";
}

// 清翔兔