调试代码时,有时会用到一种类似于头文件保护的技术,这就要用到两项预处理功能:assert和NDEBUG。
预处理器定义了几个对于程序调试很有用的名字:
__FILE__ 存放文件名的字符串字面值
__LINE__ 存放当前行号的整型字面值
__TIME__ 存放文件编译时间的字符串字面值
__DATE__ 存放文件编译日期的字符串字面值
另外还有__func__.输出当前调试的函数的名字,不过这是C++11新增的,有些老编译器不支持。
可以使用这些常量在错误消息中提供更多信息。
// primer_6_5_3.cpp : Defines the entry point for the application.
// NDEBUG预处理变量
// 输出vector内容,有条件地输出指向过程有关的信息。
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
string word;
vector<string> vec; //声明一个存放string对象的容器vec
void display_word(vector<string>,const int); //声明显示单词的函数
cout << "input the words: ('q' to over )" << endl;
cin >> word;
while(word!="q") //往vec容器内添加元素
{
vec.push_back(word);
cin >> word;
}
display_word(vec,5); //调用函数
system("pause");
return 0;
}
void display_word(vector<string> myword,const int threshold) //定义函数,第一个参数为容器名,第二个参数为阈值
{
for(int i=0;i<myword.size();i++) //遍历容器类各个对象
{
if(myword[i].size() < threshold) //如果单词长度小于阈值
cerr << "Error: " << endl //输出以下错误信息
<< __FILE__ << endl
<< "at line " << __LINE__ << endl
<< "compiled on " << __DATE__
<< "at " << __TIME__ << endl
<< "Word read was \" " << myword[i] << " \": Length too short" << endl;
else
cout << myword[i] << endl; //否则输出单词
}
}
该程序首先定义了一个vector对象vec,然后由用户自主输入一些单词,输入完成以q结束。再调用自定义函数对输入的单词进行处理,为函数传入容器对象和长度阈值,函数体做以下处理:将长度小于5的单词作为输入不符合要求的单词,输出错误信息,长度大于等于5的单词正常打印出来。
效果如下: