C++开发笔记
#ifndef 与 #define 的作用
在 C++ 开发过程中,我们经常在头文件(.h)中见到如下的代码:
#ifndef HEADERFILE_H #define HEADERFILE_H #endif
这些代码被称作include guards,其作用是在预处理阶段,阻止头文件被多次包含(preventing a header file from being included multiple times)。
当头文件被多次包含时,ifndef 会失败,该头文件变成空文件。
三行代码的具体作用是:
#ifndef // checks whether HEADERFILE_H is not declared. #define // will declare HEADERFILE_H once #ifndef generates true. #endif // is to know the scope of #ifndef i.e end of #ifndef
其实还有else语句,else指出如果前面的ifndef失败后,需要包含的代码,但一般不用。
按行读取文件并存入字符串
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream ifs;
ifs.open("text.txt",ios::in);
if (!ifs.is_open())
{
cout << "read file failed..." << endl;
return -1;
}
string buf;
while (getline(ifs, buf))
{
cout << buf << endl;
}
return 0;
}