When I press button, i want to read text file word by word. I succeeded reading line by line using this code. I think scanf_s()
is good for this code to read text file word by word, but I don't know how to apply it on here.
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();
}
}
anyone can see what's the problem?
After reading the line from CStdioFile
, use CString::Tokenize
to parse a CString
as follows:
while (rFile.ReadString(strBufferLine))
{
int pos = 0;
CString word = strBufferLine.Tokenize(" ", pos);
while (!word.IsEmpty())
{
num = atoi(word.GetString());
word = strBufferLine.Tokenize(" ", pos);
}
}
scanf
reads console input, or redirected input. fscanf
can be used to read a file which was opened with fopen
, both these methods are C.
Use std::ifstream
to open the file in C++, use >>
operator to read word by word. For example
std::string str;
std::ifstream fin("file.txt");
while (fin >> str)
{
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.