ifstream in; ofstream out;
char buff[133];
in.open("infile.dat");
out.open("outfile.dat");
while (in.getline(buff, 133))
out << buff << "/n/n"; // 錯誤:/n 非換行轉義
// 期望:每行後插入一空行
\n(反斜杠),代碼寫成 /n(正斜杠),導致輸出字面字符串 /n/n。infile.dat 不存在,in.getline 直接失敗,循環不執行,輸出文件為空。getline 行為:讀取一行(不含換行符),若文件為空或讀取失敗返回 false。#include <fstream>
#include <string>
int main() {
std::ifstream in("infile.dat");
std::ofstream out("outfile.dat");
if (!in) { std::cerr << "無法打開輸入文件\n"; return 1; }
if (!out) { std::cerr << "無法創建輸出文件\n"; return 1; }
std::string line;
while (std::getline(in, line)) {
out << line << "\n\n"; // 正確換行轉義
}
return 0;
}
| 問題 | 錯誤寫法 | 正確寫法 |
|---|---|---|
| 換行符 | /n | \n |
| 文件打開檢查 | 無 | if (!in) ... |
| 緩衝區類型 | char[] | std::string (自動擴展) |
| 行寬限制 | 固定 133 | 無限制 |
文件拷貝插入空行失敗主因是 /n 應為 \n,輔以缺少文件打開檢查。改用 std::string + std::getline 更安全、無行寬限制。養成「檢查流狀態、用標準庫字符串」習慣。