[英]mfc read text file word by word
当我按下按钮时,我想逐字阅读文本文件。 我使用此代码成功逐行阅读。 我认为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();
}
}
任何人都可以看到有什么问题?
从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)
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.