首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C/C++ 除錯技巧:標準輸入重導向與字串串流模擬輸入

     編輯:關於C++

痛點

競程或專案開發時,頻繁手動輸入測試資料極其低效。將輸入重導向至檔案、字串緩衝區,或使用格式化字串函數,可大幅提升除錯效率。

方案一:檔案輸入重導向

C++ (fstream)

#include <fstream>
#include <iostream>
using namespace std;

int main() {
    ifstream cin("in.txt"); // 取代標準 cin
    if (!cin) {
        cerr << "開啟檔案失敗!" << endl;
        return 1;
    }
    int a, b;
    cin >> a >> b; // 直接從檔案讀取
    cout << "Sum: " << a + b << endl;
    cin.close();
    return 0;
}

C (freopen)

#include <stdio.h>
int main() {
    freopen("in.txt", "r", stdin); // stdin 重導向
    int a, b;
    scanf("%d %d", &a, &b);
    printf("Sum: %d\n", a + b);
    fclose(stdin);
    return 0;
}

方案二:字串緩衝區模擬輸入 (無需檔案)

C++ (istrstream / stringstream)

#include <strstream> // 舊標準,建議用 <sstream>
#include <iostream>
using namespace std;

int main() {
    char input[] = "10 20\n30 40"; // 測試資料
    istrstream cin(input); // 或 istringstream cin(input);
    int a, b, c, d;
    cin >> a >> b >> c >> d;
    cout << a << ' ' << b << ' ' << c << ' ' << d << endl;
    return 0;
}

C (sscanf)

#include <stdio.h>
int main() {
    char buffer[] = "10 20 30";
    int a, b, c;
    sscanf(buffer, "%d %d %d", &a, &b, &c);
    printf("%d %d %d\n", a, b, c);
    return 0;
}

方案三:字串格式化輸出/輸入 (sprintf / sscanf)

函數用途原型
sprintf格式化資料寫入字串緩衝區int sprintf(char *buf, const char *fmt, ...);
snprintf安全版 (防緩衝區溢位)int snprintf(char *buf, size_t n, const char *fmt, ...);
sscanf從字串解析格式化資料int sscanf(const char *buf, const char *fmt, ...);
// 範例:組合 SQL 查詢字串 / 解析日期
char sql[256];
sprintf(sql, "SELECT * FROM users WHERE id=%d AND name='%s'", 1001, "Alice");

char date[] = "2024-12-25";
int y, m, d;
sscanf(date, "%d-%d-%d", &y, &m, &d);
// y=2024, m=12, d=25

進階技巧:條件編譯切換輸入源

#define DEBUG_INPUT 1

int main() {
#if DEBUG_INPUT
    ifstream cin("testcase.in");
#else
    // 正常使用 std::cin
#endif
    // ... 統一的讀取邏輯
}

總結建議

  • 競程:用 freopen 或直接管線 ./a.out < in.txt (Linux/Mac) 最快。
  • Visual Studio 專案:專案屬性 → 偵錯 → 命令引數,或在程式碼用 ifstream 讀取專案目錄下的檔案。
  • 單元測試:善用 stringstream / sscanf 將測試向量內嵌在程式碼中,無外部依賴。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved