MFC 如何用 `fscanf` 讀取不定數量的變量?用數組接收如何取地址?
用循環配合 `fscanf` 返回值判斷 EOF,逐個讀入數組元素。
FILE* fp = fopen("data.txt", "r");
if (!fp) return;
float vals[1000]; // 足夠大的緩衝區
int count = 0;
float temp;
while (fscanf(fp, "%f", &temp) == 1) { // 成功讀取 1 個 float
if (count < 1000) vals[count++] = temp;
else break; // 防溢出
}
fclose(fp);
// 現在 count 為實際讀取數量,vals[0..count-1] 存有數據
MFC 提供 `CStdioFile` 配合 `ReadString` 逐行讀取,再用 `sscanf`/`CString::Tokenize` 解析,更符合 MFC 風格且支援 Unicode:
CStdioFile file;
if (file.Open(_T("data.txt"), CFile::modeRead | CFile::typeText)) {
CString line;
while (file.ReadString(line)) {
// 解析 line...
}
file.Close();
}