单文档视图已经建好了,读取文件的类还有其他的代码怎么搞啊

按要求编程实现如下功能:

1.新建单文档视图

2.读取文件stu_ANSI.txt, 读取文件中的学生列表名称,显示到视图中,

3.在视图中并鼠标左键选中某行,标出红框显示

要求实现一个类 CStuInfo

实现其拷贝构造函数,赋值运算符=重载

提示:

新建单文档视图工程,注意修改字符集 为多字节字符集

加载文件 重载Doc中的OpenDocument

在View中OnDraw中绘制文本

在WM_LBUTTONDOWN中添加选择处理

TechWhizKid参考GPT回答:

  • 基于Microsoft Foundation Classes (MFC)的项目中,读取文件,处理用户输入,以及在视图中显示数据涉及到几个主要的组件:CDocument,CView,和CMainFrame。同时要一个CStuInfo类来存储学生信息。

先创建CStuInfo类:

class CStuInfo
{
public:
    CString m_strName; // 学生名称

    // 构造函数
    CStuInfo() {}

    // 拷贝构造函数
    CStuInfo(const CStuInfo& other)
    {
        m_strName = other.m_strName;
    }

    // 赋值运算符重载
    CStuInfo& operator=(const CStuInfo& other)
    {
        if(this != &other)
        {
            m_strName = other.m_strName;
        }
        return *this;
    }
};

接下来在CDocument派生类中添加一个CStuInfo对象列表:

class CMyDoc : public CDocument
{
protected:
    std::vector<CStuInfo> m_vecStuInfos; // 存储学生信息的列表

public:
    // 重载OpenDocument以打开和读取stu_ANSI.txt
    virtual BOOL OnOpenDocument(LPCTSTR lpszPathName) override
    {
        CStdioFile file;
        if(!file.Open(lpszPathName, CFile::modeRead | CFile::typeText))
        {
            return FALSE;
        }

        CString strLine;
        while(file.ReadString(strLine))
        {
            CStuInfo stuInfo;
            stuInfo.m_strName = strLine;
            m_vecStuInfos.push_back(stuInfo);
        }

        file.Close();

        return TRUE;
    }
};

然后在CView派生类中处理数据显示和用户交互:

class CMyView : public CScrollView
{
private:
    int m_nSelectedLine; // 记录选中的行

protected:
    // 在OnDraw中绘制学生信息
    virtual void OnDraw(CDC* pDC) override
    {
        CMyDoc* pDoc = GetDocument();
        ASSERT_VALID(pDoc);

        int nY = 0;
        for(int i = 0; i < pDoc->m_vecStuInfos.size(); i++)
        {
            if(i == m_nSelectedLine)
            {
                // 如果是选中的行,用红色绘制
                pDC->SetTextColor(RGB(255, 0, 0));
            }
            else
            {
                // 否则用黑色
                pDC->SetTextColor(RGB(0, 0, 0));
            }

            pDC->TextOutW(0, nY, pDoc->m_vecStuInfos[i].m_strName);
            nY += 20; // 例如每行间距20像素
        }
    }

    // 在WM_LBUTTONDOWN中处理选择行
    virtual void OnLButtonDown(UINT nFlags, CPoint point) override
    {
        m_nSelectedLine = point.y / 20; // 假设每行20像素
        Invalidate(); // 重新绘制视图
        CScrollView::OnLButtonDown(nFlags, point);
    }
};