2 回答

TA貢獻1831條經驗 獲得超10個贊
以下是源代碼,基于MFC的控制臺程序,如果需要cpp文件的話,請告訴我你的郵箱。
// timeRead.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "timeRead.h"
#include <fstream>
#include <iomanip>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
CWinApp theApp;
using namespace std;
/*
* @Func : 往文件流out中寫入信息,格式為時間:: 內容
*/
void write(ostream &out, const CTime &t)
{
static int cnt = 0; // 當前記錄條數
CString szTmp;
// 在時間和內容之間插入一標識符::,起分隔作用,方便提取時間對應的內容
szTmp.Format("%s:: 于%s寫入 第%i條記錄", t.Format("%Y%m%d"), t.Format("%Y年%m月%d日 %H時%M分%S秒"), ++cnt);
out << LPCSTR(szTmp) << endl;
}
/*
* @Func : 解析格式信息,時間:: 內容,并返回信息
*
* @Parm [in ] szRcdInfo : 記錄信息,格式為:時間:: 內容
* @Parm [out] szTime : 時間部分
* @Parm [out] szInfo : 內容部分
*
* @Ret : true格式正確,false格式不正確
*/
bool getInfo(const CString &szRcdInfo, CString &szTime, CString &szInfo)
{
int index = szRcdInfo.Find("::", 0);
if (index == -1) return false;
szTime = szRcdInfo.Left(index);
szInfo = szRcdInfo.Mid(index+2);
return true;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
ofstream out("output.txt");
if (!out)
for (int i = 0; i < 10; ++i)
write(out, CTime::GetCurrentTime()); // CTime::GetCurrentTime()用于獲取當前系統時間
out.close();
// 讀取文件
ifstream in("output.txt");
if (!in)
CString szRcdInfo, szTime, szInfo;
char buffer[100];
while(in.getline(buffer, 100))
{
szRcdInfo = buffer;
getInfo(szRcdInfo, szTime, szInfo);
cout.flags(cout.flags()|ios::left); // 設置左對齊,默認為右對齊
cout << "[時間] "<< setw(10) << LPCSTR(szTime) << "[內容] " << LPCSTR(szInfo) << endl;
}
}
return nRetCode;
}
以下是我電腦上的輸出結果:
[時間] 20100830 [內容] 于2010年08月30日 15時21分08秒寫入 第1條記錄
[時間] 20100830 [內容] 于2010年08月30日 15時21分08秒寫入 第2條記錄
[時間] 20100830 [內容] 于2010年08月30日 15時21分08秒寫入 第3條記錄
[時間] 20100830 [內容] 于2010年08月30日 15時21分08秒寫入 第4條記錄
[時間] 20100830 [內容] 于2010年08月30日 15時21分08秒寫入 第5條記錄
[時間] 20100830 [內容] 于2010年08月30日 15時21分08秒寫入 第6條記錄
[時間] 20100830 [內容] 于2010年08月30日 15時21分08秒寫入 第7條記錄
[時間] 20100830 [內容] 于2010年08月30日 15時21分08秒寫入 第8條記錄
[時間] 20100830 [內容] 于2010年08月30日 15時21分08秒寫入 第9條記錄
[時間] 20100830 [內容] 于2010年08月30日 15時21分08秒寫入 第10條記錄

TA貢獻1851條經驗 獲得超3個贊
1、不用using namespace std;如何使用string類,可以單獨聲明:using std::string;想使用ctring頭文件中的函數,直接#include <cstring>就行了。
2、如果在C++中要使用C庫中的內容,可以直接使用C頭文件的格式,即time.h,在C++中推薦使用ctime,即幾乎每個C的頭文件在C++里面都把.h去掉,在前面加上c。
3、#include"XXXXXX.h" 代表編譯的時候先去用戶指定的目錄去查找,然后再到系統庫去尋找。
與#include<XXXXXX.h>代表直接去系統庫去查找,#include<XXXXXX>一般是C++中一些常用類庫(新增的)。
4、using namespace std代表把std命名空間中所有定義的東西都引用進來,若要單獨使用某個定義在std里面的內容,使用using std::XXX就可以了。
- 2 回答
- 0 關注
- 416 瀏覽
添加回答
舉報