Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C kiểm tra từ khóa (Keyword)

Giới thiệu

Từ khóa (Keyword) là từ dành riêng, có nghĩa cố định trong ngôn ngữ, không thể dùng làm tên biến. C có 32 từ khóa, C++ có thêm 30 từ khóa riêng.

Danh sách từ khóa C (32)

autodoubleintstruct
breakelselongswitch
caseenumregistertypedef
charexternreturnunion
constfloatshortunsigned
continueforsignedvoid
defaultgotosizeofvolatile
doifstaticwhile

Từ khóa riêng C++ (30)

asmdynamic_castnamespacereinterpret_cast
boolexplicitnewstatic_cast
catchfalseoperatortemplate
classfriendprivatethis
const_castinlinepublicthrow
deletemutableprotectedtrue
trytypeidtypenameusing
virtualwchar_t

Thuật toán

Nhập chuỗi str
Duyệt mảng keyword[32]:
  Nếu strcmp(str, keyword[i]) == 0 → là từ khóa
In kết quả

Code C

#include <stdio.h>
#include <string.h>

int main() {
    char keyword[32][10] = {
        "auto","double","int","struct","break","else","long",
        "switch","case","enum","register","typedef","char",
        "extern","return","union","const","float","short",
        "unsigned","continue","for","signed","void","default",
        "goto","sizeof","volatile","do","if","static","while"
    };
    char str[] = "for";
    int flag = 0, i;

    for (i = 0; i < 32; i++) {
        if (strcmp(str, keyword[i]) == 0) {
            flag = 1;
            break;
        }
    }

    if (flag)
        printf("%s is a keyword", str);
    else
        printf("%s is not a keyword", str);
    return 0;
}

Kết quả

for is a keyword

Lưu ý

  • Code gốc có lỗi gõ: "voltile" → sửa thành "volatile"
  • Chương trình chỉ kiểm tra từ khóa C, chưa bao gồm C++
  • Có thể mở rộng bằng cách đọc input từ bàn phím