Essential C++ 学习笔记1

练习1.5

撰写一个程序,使之能够询问用户姓名,并读取用户所输入的内容。请确保用户输入的名称长度大于两个字符。如果用户的确输入了有效信息,就响应一些信息。

#include 
#include   // C-Style 
#include 
using namespace std;

int main()
{
    const int nm_size = 128;
    char user_name[nm_size];
    cout << "please enter your name:\n";
    cin >> setw(nm_size) >> user_name;

    switch (strlen(user_name))
    {
        case 127:
            cout <<"That is a vary big name!\n";
            //no break
        default:
            cout <<"Hello,"<< user_name<<setfill('*')<<setw(10)
                  <<"--happy to make your acquaintance!\n";
            break;
    }
    return 0;
}

练习1.6

编写一个程序,从标准输入设备读取一串整数,并将读入的整数依次放到array及vector,然后遍历这两种容器,求取数值综合。将总和及平均值输出至标准输出设备。

array的大小必须固定,vector可以动态地随着元素的插入而扩展储存空间。
array并不储存自身大小

#include 
#include 
using namespace std;

void ex1_6_vector() 
{
    vector<int> ivec;
    int ival;

    while ( cin >> ival ) 
            ivec.push_back( ival );

    // we could have calculated the sum as we entered the
    // values, but the idea is to iterate over the vector ...
	int sum = 0;
    for ( int ix = 0; ix < ivec.size(); ++ix )
	{
		  cout << endl << ix << ") " << ivec[ ix ];
          sum += ivec[ ix ]; }

    int average = sum / ivec.size();
    cout << "Sum of " << ivec.size()
         << " elements: " << sum
         << ". Average: " << average << endl;
}

void ex1_6_array() 
{
    const int arr_size = 128;
	int ia[ arr_size ];
    int ival, icnt = 0;

    while ( cin >> ival && icnt < arr_size ) 
            ia[ icnt++ ] = ival;
           
    // icnt is 1 greater than number of elements!
	int sum = 0;
    for ( int ix = 0; ix < icnt; ++ix )
          sum += ia[ ix ];

    int average = sum / icnt;
    cout << endl 
		 << "Sum of " << icnt
         << " elements: " << sum
         << ". Average: " << average << endl;
}

练习1.7
使用你最称手的编辑工具,输入两行(或更多)文字并存盘。然后编写一个程序,打开该文本文件,将其中每个字都读取到一个vector对象中。遍历该vector,将内容显示到cout。然后利用泛型算法sort(),对所有文字排序:

#include
sort( container.begin(),container.end() );

再将排序后的结果输出到另一个文件。

你可能感兴趣的:(c++)