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

C語言鍵盤輸入完全指南:scanf、getchar、gets詳解

     編輯:C 語言基礎

輸入函數概覽

程序是人機交互的媒介,有輸出必有輸入。C 語言提供多種從鍵盤獲取用戶輸入的函數:

  • scanf():格式化輸入,支援多種數據類型,最靈活、最常用。
  • getchar()、getche()、getch():輸入單個字符,行為略有差異。
  • gets():讀取整行並作為字符串處理。

scanf() 雖強大,但無法完全取代其他函數,各有適用場景。

scanf() 函數深度解析

scanf 是 scan format 縮寫,意為「格式化掃描」。先看基礎示例:

#include <stdio.h>
#include <stdlib.h>
int main() {
    int a, b, c, d;
    scanf("%d", &a);  // 輸入整數賦值給 a
    scanf("%d", &b);  // 輸入整數賦值給 b
    printf("a+b=%d\n", a+b);
    scanf("%d %d", &c, &d); // 同時輸入兩個整數
    printf("c*d=%d\n", c*d);
    system("pause");
    return 0;
}

運行結果:
12↙
60↙
a+b=72
10 23↙
c*d=230

↙ 表示按下回車鍵。每按一次回車,scanf() 讀取並提取數據。

關鍵點:& 取地址符

scanf("%d %d", &a, &b); // 變量前必須加 &
printf("%d %d", a, b);    // 輸出不需要 &

& 稱為「取地址符」,獲取變量在內存中的地址。scanf 根據地址將讀取的數據寫入內存。這與 printf 形成鮮明對比。

內存地址演示

#include <stdio.h>
#include <stdlib.h>
int main() {
    int a = 'F', b = 12, c = 452;
    printf("&a=%#x, &b=%#x, &c=%#x\n", &a, &b, &c);
    system("pause");
    return 0;
}

輸出:
&a=0x18ff48, &b=0x18ff44, &c=0x18ff40

注意:這是虛擬地址,非物理內存地址,現代作業系統為內存管理引入的概念。

scanf 格式控制字符串的靈活性

scanf("%d %d", &a, &b);        // 空格分隔
scanf("%d, %d, %d", &a, &b, &c); // 逗號分隔
scanf("%d is bigger than %d", &a, &b); // 字符串分隔

scanf 對輸入數據間空白字符的處理較寬鬆,多個空格、換行、Tab 均視為分隔符;但若格式字符串包含非空白字符(如逗號、特定單詞),輸入必須嚴格匹配。

連續讀取與讀取失敗問題

一次性輸入多個值:

12 60 10 23↙
a+b=72
c*d=230

scanf 會保留緩衝區中未讀取的內容供下次使用。但若格式不匹配,可能導致後續 scanf 被「跳過」:

scanf("a=%d", &a); // 輸入 a=100↙
scanf("b=%d", &b); // 此句被忽略,b 保持初值 0

這涉及 C 語言輸入緩衝區機制,後續專題詳細講解。

單字符輸入三兄弟:getchar / getche / getch

getchar() —— 標準、帶緩衝、需回車

#include <stdio.h>
#include <stdlib.h>
int main() {
    char c = getchar();
    printf("c='%c'\n", c);
    system("pause");
    return 0;
}

運行:#↙ → c='#'
必須按回車確認,有回顯(輸入字符顯示在屏幕)。

getche() —— 非標準、無緩衝、即時獲取、有回顯

#include <stdio.h>
#include <conio.h>  // 需此頭文件
#include <stdlib.h>
int main() {
    char c = getche();
    printf("c='%c'\n", c);
    system("pause");
    return 0;
}

運行:# → c='#'
輸入即獲取,無需回車,有回顯。conio.h 非標準頭文件,移植性較差。

getch() —— 非標準、無緩衝、即時獲取、無回顯

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main() {
    char c = getch();
    printf("c='%c'\n", c);
    system("pause");
    return 0;
}

運行:輸入 # 無顯示 → c='#'
無回顯,適合輸入密碼等敏感信息。

本質上,getch()/getche() 無緩衝即時響應;getchar() 帶緩衡需回車確認。getchar() 屬標準 C(stdio.h),前兩者屬擴展(conio.h),不保證所有編譯器支援。

字符串輸入:gets() vs scanf()

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main() {
    char str1[30], str2[30];
    gets(str1);          // 讀取整行(含空格)
    scanf("%s", str2);   // 遇空格停止
    puts(str1);
    puts(str2);
    system("pause");
    return 0;
}

運行:
The world is beautiful!↙
Hello World!↙
The world is beautiful!
Hello

gets() 讀取整行含空格;scanf("%s") 遇空格截斷。注意:gets() 不安全(無長度檢查),現代 C 建議用 fgets() 替代。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved