控制符

可以通过控制符设置输出数字的进制,小数点保留位数,字符串宽度等设置。

cout << "Integer in octal: " << oct << 11 << endl;
cout << "Integer in octal: " << hex << 11 << endl;
cout << setprecision(4);
cout << fixed << 7.4;
cout << setw(35);
cout << "Hello"<<endl;

cin::get()

输入字符串时,应使用cin.get函数,如果直接使用cin »,可能会导致内存溢出错误。当然可以直接使用string类,这样就不会有该问题了。

char charBuf[10] = { 0 };
//cin >> charBuf; //Danger: user may enter more than 10 chars
cin.get(charBuf, 9);
cout << "charBuf: " << charBuf << endl;

string name;
cin >> name; //name不能有空白,空白字符会自动断开
cout << name;

getline(cin, name);

文件读写

fstream myFile;
myFile.open("hello.txt", ios_base::in | ios_base::out | ios_base::app);
if (myFile.is_open()) {
	cout << "File open successful" << endl;

	string str;
	myFile << "My first text filesdf!" << endl;
	myFile.seekg(ios::beg);
	myFile >> str;

	cout << str;

	myFile.close();
}

API

CreateDirectory

创建文件夹,第一个参数是路径,第二个参数是可选的文件属性

if (!::PathFileExists(szPath))
{
	::CreateDirectory(szPath, NULL);
}

PathFileExists

确定文件是否存在

PathCombine

将表示正确格式路径的两个字符串连接成一个路径,第一个参数pszDest为返回连接后的文件路径,第二个参数pszDir为文件目录,第三个参数pszFile为文件名。如果返回的目录路径以反斜杠结尾,则将保留反斜杠

wchar_t pszDest[MAX_PATH] = L"";
wcout << PathCombine(pszDest, _T("C:\\Documents"), _T("RobotStudio\\system.xml")) << endl;
wcout << PathCombine(pszDest, _T("C:\\Documents\\"), _T("RobotStudio\\system.xml")) << endl;
wcout << PathCombine(pszDest, _T("C:\\Documents"), _T("RobotStudio\\")) << endl;

C:\Documents\RobotStudio\system.xml
C:\Documents\RobotStudio\system.xml
C:\Documents\RobotStudio\

PathRemoveFileSpec

从路径中删除尾随文件名和反斜杠(如果存在)。

wchar_t pszDest[MAX_PATH] = L"";
wcout << PathCombine(pszDest, _T("C:\\Documents"), _T("RobotStudio\\system.xml")) << endl;
wcout << PathCombine(pszDest, _T("C:\\Documents"), _T("RobotStudio\\")) << endl;

PathRemoveFileSpec(pszDest);
wcout << pszDest << endl;

C:\Documents\RobotStudio\system.xml => C:\Documents\RobotStudio
C:\Documents\RobotStudio\ => C:\Documents\RobotStudio

GetModuleFileName

获取dll或exe的文件路径,第一个参数为dll句柄,如果为NULL,则获取的是当前dll或exe的文件路径。第二个参数lpFilename为返回的路径。第三个参数为lpFilename的大小,非返回文件路径的大小,而是定义的字符串数组的长度,因为第二个长度是指针,该函数需要知道这个指针指向字符串数组的长度,防止数据溢出。

wchar_t szAppPath[MAX_PATH];
::GetModuleFileName(NULL, szAppPath, MAX_PATH);
wcout << szAppPath << endl;