基本语言

2014-09-14  本文已影响38人  eesly_yuan
变量与基本类型

类类型初始化,如果未显示提供初始化式,则调用默认构造函数初始化。

标准库类型
数组和指针
typedef string *pstring;
const pstring cstr ;等效于 string * const cstr; 前面那个const是修饰pstring
strlen(s)
strcmp(s1,s2)
strcat(s1,s2)
strcpy(s1,s2)
strncat(s1,s2,n)
strncpy(s1,s2,n)

上述函数的调用者必须保证目标字符串有足够的大小
尽可能使用string而不是上述的c风格的字符串

表达式
+(正号)、-(负号)
*、/、%
+、-
!
<、<=、>、>=
==、!=
&&
||
~
<<、>>
&、^、|
sizeof(type name)
sizeof expr
sizeof(expr)
语句
try{ st1
}catch(exc1){handle1
}catch(exc2){handle2
}
最常见的问题
exception
-
运行时错误
runtime_error
range_error
overflow_error
underflow_error
逻辑错误
-
logic_error
domain_error
invalid_error
length_error
out_of_error
__FILE__文件名
__LINE__当前行号
__TIME__文件被编译的时间
__DATE__文件被编译的日期

还有一个有用的工具是assert(断言)预处理宏,频繁的调用会极大的影响程序的性能,增加额外的开销。在调试结束后,可以通过在包含#include <assert.h>的语句之前插入 #define NDEBUG 来禁用assert调用。

一个非常简单的使用assert的规律就是,在方法或者函数的最开始使用,如果在方法的中间使用则需要慎重考虑是否是应该的。方法的最开始还没开始一个功能过程,在一个功能过程执行中出现的问题几乎都是异常。

函数
标准IO库
    //字符串逆序
    string inputLine;
    getline(cin,inputLine);
    istringstream inputLineStream(inputLine);
    string word;
    vector<string> wordVec;
    while(inputLineStream>>word)
        wordVec.push_back(word);
    //逆序打印
    vector<string>::reverse_iterator rit = wordVec.rbegin();
    while(rit!=wordVec.rend())
    {
        if (rit == wordVec.rbegin())
            cout<<*rit++;
        else
            cout<<" "<<*rit++;
    }
    cout<<endl;

in读权限
out写权限,文件会被清空,同时以in和out打开不清空
app追加
ate定位文件尾
trunc清空打开的文件内容
binary二进制打开

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
const int FILE_NUM = 5;
int main()
{
   //建立文件名
   vector<string> svec;
   string s("file");
   for (int i = 0; i<FILE_NUM; i++)
   {
       stringstream filename;
       filename<<"file"<<i<<".txt";
       svec.push_back(filename.str());
   }
   //打开文件并写入数据
   ofstream ofile;
   for(vector<string>::iterator it = svec.begin();it!=svec.end();it++)
   {
       ofile.open(it->c_str());
       if (!ofile)
       {
           cerr<<"open out file failed!";
           system("pause");
           return -1;
       }
       stringstream text;
       text<<"this is "<<it->c_str()<<endl;
       ofile<<text.str();
       ofile.close();
       ofile.close();
   }

   //读取内容
   ifstream ifile;
   for(vector<string>::iterator it = svec.begin();it!=svec.end();it++)
   {
       ifile.open(it->c_str());
       if (!ifile)
       {
           cerr<<"open in file failed!";
           system("pause");
           return -1;
       }
       string line,word;
       vector<string> wordvec;
       getline(ifile,line);//获取一行数据
       istringstream linestream(line);
       while (linestream>>word)
           wordvec.push_back(word);
       ifile.close();
       ifile.clear();

       //打印
       vector<string>::reverse_iterator rit = wordvec.rbegin();
       while(rit!=wordvec.rend())
       {
           cout<<*rit<<" ";
           rit++;
       }
       cout<<endl;
   }
   system("pause");
}
上一篇 下一篇

猜你喜欢

热点阅读