1. std::count
原文地址:http://www.cnblogs.com/devymex/archive/2010/09/06/1818754.html
cout是C++终端输出函数,类似于C的printf。
下面是我给合原文所写的测试代码:
void TestCout()
{
cout.setf(ios::showpos | ios::uppercase); // 显示符号“+-”,十六进制大写输出
cout << hex << setw(4) << 12 << setw(12) << -12 << endl; // 十六进制
cout << dec << setw(4) << 12 << setw(12) << -12 << endl; // 十进制
cout << oct << setw(4) << 12 << setw(12) << -12 << endl; // 八进制
cout.unsetf(ios::showpos | ios::uppercase); // 反转标志
cout << hex << setw(4) << 12 << setw(12) << -12 << endl;
cout << dec << setw(4) << 12 << setw(12) << -12 << endl;
cout << oct << setw(4) << 12 << setw(12) << -12 << endl;
cout.setf(ios::fixed); // 浮点精度
cout << setprecision(0) << 12.05 << endl;
cout << setprecision(1) << 12.05 << endl;
cout << setprecision(2) << 12.05 << endl;
cout << setprecision(3) << 12.05 << endl;
cout.setf(ios::scientific, ios::floatfield); // 指数表示
cout << setprecision(0) << 12.05 << endl;
cout << setprecision(1) << 12.05 << endl;
cout << setprecision(2) << 12.05 << endl;
cout << setprecision(3) << 12.05 << endl;
}
2. fstream
fstream用于文件的流操作。文件输入流ifstream和文件输出流ofstream都是fstream的子类。
void open (const char* filename,
ios_base::openmode mode = ios_base::in | ios_base::out);
mode: 打开模式,包括以下:
下面为测试代码:
void TestFstream()
{
//
// ofstream 文件输出
char *pBuffer = "This is my test buffer for fstream.\nThe Second line.";
ofstream ofs;
ofs.open(TEXT("test.txt"), ios::out); // ios::app 追加
ofs.write(pBuffer, strlen(pBuffer));
ofs.close();
//
// ifstream 文件输入
ifstream ifs;
ifs.open(TEXT("test.txt"), ios::in);
if (!ifs.is_open())
{
return;
}
char rdBuffer[17] = {0};
streampos sp;
while (!ifs.eof())
{
sp = ifs.tellg(); // 获取当前文件指针位置
cout << "[" << dec << sp << "]";
ifs.read(rdBuffer, 16);
cout << rdBuffer;
memset(rdBuffer, 0, 17);
}
cout << flush << endl;
ifs.close();
//
// getline的使用
ifs.clear(); // 重复利用,调用clear重置流状态
ifs.open(TEXT("test.txt"), ios::in);
char line[257] = {0};
while (!ifs.eof())
{
sp = ifs.tellg();
cout << "[" << dec << sp << "]";
ifs.getline(line, 256); // 确保文件每一行不超过buffer的大小
cout << line;
memset(line, 0, 256);
}
cout << endl;
ifs.close();
}