【问题标题】:MFC Reading text file word by wordMFC逐字读取文本文件
【发布时间】:2022-01-16 14:26:10
【问题描述】:

当我按下按钮时,我想逐字阅读文本文件。我使用此代码成功逐行阅读。我认为scanf_s() 适合此代码逐字读取文本文件,但我不知道如何在此处应用。

void CFileloadView::OnBnClickedButton1()
{
    CFileDialog dlg(TRUE, _T("*.txt"), NULL, OFN_FILEMUSTEXIST | OFN_OVERWRITEPROMPT,
             _T("TXT Files(*.txt)|*.txt|"), NULL);
    if (dlg.DoModal() == IDOK)
    {
        CStdioFile rFile;
        CString strBufferLine;
        int count = 0;

        int num;

        if (!rFile.Open(dlg.GetPathName(), CFile::modeRead))
        {
            MessageBox(_T("Can't OpenFile!"), _T("Warning"), MB_OK | MB_ICONHAND);
            return;
        }

        while (rFile.ReadString(strBufferLine)) 
        {
            //fscanf(rFile, "%d", &num);

            count++;
            m_list2.AddString(strBufferLine);
            strBufferLine.Replace(("\r"), ("")); 

            if (strBufferLine.GetAt(0) == '#')
                continue; 
        }
        rFile.Close();
    }
}

谁能看出问题所在?

【问题讨论】:

  • 请注意,最后一个 if 语句什么都不做:while 循环将 continue 无论如何。

标签: c++ mfc


【解决方案1】:

读取来自CStdioFile的行后,使用CString::Tokenize解析CString如下:

while (rFile.ReadString(strBufferLine))
{ 
    int pos = 0;
    CString word = strBufferLine.Tokenize(" ", pos);
    while (!word.IsEmpty())
    {
        num = atoi(word.GetString());
        word = strBufferLine.Tokenize(" ", pos);
    }
}

scanf 读取控制台输入或重定向输入。 fscanf可以用来读取用fopen打开的文件,这两种方法都是C。

使用std::ifstream在C++中打开文件,使用>>操作符逐字读取。例如

std::string str;
std::ifstream fin("file.txt");
while (fin >> str)
{
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2015-05-13
    相关资源
    最近更新 更多