The function of the fscanf() function is to read one or more data in a format from a file;
For example, there is a row of data in the file,
22 3.34 hello
Then use fscanf(fp, "%d%f%s", &a, &f, str) to read integer, floating point, and string data at one time;
This function is located in the C standard library header file <stdio.h>;
Example;
The test files are as follows;
code;
void CFiletest1View::OnDraw(CDC* pDC)
{
CFiletest1Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
int a = 0;
float f = 0;
char str[100] = "";
CString str1;
int d=0;
float f2=0;
FILE* fp = fopen("test1.txt", "r");
for(int i=0; i<3; i++)
{
fscanf(fp, "%d%f%s", &a, &f, str);
str1.Format("%d,%f,%s", a, f, str);
pDC->TextOut(50, 50 + i*20, str1);
d += a;
f2 += f;
}
str1.Format("整数和:%d", d);
pDC->TextOut(50, 115, str1);
str1.Format("浮点数和:%f", f2);
pDC->TextOut(50, 135, str1);
fclose(fp);
}
Run as follows;
The CStdioFile class is often used in MFC; can I still use the fscanf() function?
First, take a look. After using the CStdioFile class to open a file, the BOOL type is returned, and fscanf requires a FILE* type; if the file is opened with the C standard library function fopen, the FILE* type is returned;
Check the MFC documentation;
The CStdioFile class has a member m_pStream,
CStdioFile::m_pStream
The m_pStream data member is a pointer to an open file returned by the C runtime function fopen. It is NULL if the file has never been opened or has been closed.
According to the documentation, this m_pStream is the return value of the C standard library function fopen after opening the file;
Then change it to the following code and take a look;
void CFiletest1View::OnDraw(CDC* pDC)
{
CFiletest1Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
int a = 0;
float f = 0;
char str[100] = "";
CString str1;
int d=0;
float f2=0;
CStdioFile file;
file.Open("test1.txt", CFile::modeRead);
for(int i=0; i<3; i++)
{
//根据字符类型读取txt文件中的数据
fscanf(file.m_pStream, "%d%f%s", &a, &f, str);
str1.Format("%d,%f,%s", a, f, str);
pDC->TextOut(50, 50 + i*20, str1);
d += a;
f2 += f;
}
str1.Format("整数和:%d", d);
pDC->TextOut(50, 115, str1);
str1.Format("浮点数和:%f", f2);
pDC->TextOut(50, 135, str1);
file.Close();
}
Run it; no problem, same;