读书笔记_chapter1

来源:互联网 发布:怎样投诉淘宝盗图 编辑:程序博客网 时间:2024/06/05 23:59

1. Setw( size )的使用方法:

#include <iomanip>  //setw(int asize)

const int nm_size = 128;

char user_name[ nm_size ];

cin >> setw( nm_size ) >> user_name;

如输入的字符个数超过nm_size, 则取前nm_size -1 个字符给数组,数组中最后一个元素自动设为空字符。

 

2. 利用cin 作为循环条件。

如vector<int> ivec;

    int ival;

    while ( cin >> ival )

            ivec.push_back( ival );

如果输入非整数,则cin 返回 false, 循环结束。

同时在这几条语句中我们也看到了vector的用法。Ivec.push_back(ival).

 

3. isdigit(char c ) 的用法,判断一个字符是否是数字 0-9.

char a; char *p, p[]; string p;

isdigit( a ) 或 isdigit(p[0])

当a 或 p[0]为数字0-9时,返回非零值,否则返回零

 

4. vector 的元素是一个字符串指针,指向一个字符串

       vector< string* > sp_vec;

       string st;

       while ( cin >> st && !( st.length() == 1 && st[0] == ‘0’ ) )

                  sp_vec.push_back( new string( st ));

为什么这里要new 一个 string 对象放到vector 中去?

因为要取多个string。

 

5. vector中的iterator

       vector<string*>::iterator

              iter = sp_vec.begin(),

              it_end = sp_vec.end();

iter 将指向vector 中第一个元素。

It_end将指向vector中最后一个元素。

 

6. 文件操作

    string file_name;

    cin >> file_name;

    if ( ! cin || file_name.empty() )

       { cerr << "oops! unable to read file name/n"; return; }

    ifstream ifile( file_name.c_str() ); //文件必须存在,否则打开失败。

 


 

file_name += ".sort";//若文件不存在,将创建一个文件。

ofstream ofile( file_name.c_str() );

 

fstream iofile(file_name.c_str(), ios_base::in|ios_base::app); 以读写和追加方式打开。

seekg(0); 重定位文件指针函数

 

读取:  

string word;

    vector< string > text;

    while ( ifile >> word )

                        text.push_back( word );

排序: sort( text.begin(), text.end() );  // #include <algorithm>

输出:

int cnt = 0;

    for ( vector<string>::iterator iter = text.begin();   //定义了一个指针iter,指向Vector text中的元素。

          iter != text.end(); ++iter )

    {

                    cnt += iter->size()+1; // iter->size() 指该字符串的长度

                     if ( cnt > 40 ) {

                              ofile << '/n'; cnt = 0; } //每行小于40个字符

                     ofile << *iter << ' ';

       }

 

普通的输出方法:

       for (int ix = 0; ix < text.size(); ++ix )

                ofile << text[ ix ] << ' ';

 

7. 指针补充
定义一个指针,指向一个一个数组,定义一个指向具有4个float元素的一维数组的指针:float  (*p)[4]  //相当于二维数组的数组名

定义一个数组:vector <string>*     P[4];  //数组中的元素是:vector<string> *

 

8.结束程序

#include <cstdlib>

exit(-1);

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sanfengshou/archive/2009/08/30/4500153.aspx

原创粉丝点击