輸入多行字符串,判斷每行是否為 C 語言合法標識符。
規則:
1. 首字符只能是字母 (A-Z, a-z) 或下劃線 '_'
2. 其餘字符只能是字母、數字 (0-9) 或下劃線
長度 ≤ 50,多測試用例。
getline 更稳妥)isalpha(s[0]) || s[0]=='_'isalnum(c) || c=='_'#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
int n; string s;
cin >> n; getchar(); // 吸收換行
while (n--) {
getline(cin, s);
bool ok = true;
if (s.empty() || !(isalpha(s[0]) || s[0] == '_')) ok = false;
for (char c : s)
if (!(isalnum(c) || c == '_')) { ok = false; break; }
cout << (ok ? "yes" : "no") << endl;
}
return 0;
}
輸入: 3 12ajf fi8x_a ff ai_2 輸出: no yes no
12ajf:首字符是數字 → nofi8x_a:首字母,其餘字母數字下劃線 → yesff ai_2:含空格 → no (空格非字母數字下劃線)int) 在 C 標準中也是合法標識符 (雖不能作變量名),本題不排除關鍵字isalpha 涵蓋 A-Z/a-zgetline 會讀入,需按題意決定是否 trim;樣例第三行 ff ai_2 含中間空格直接判非法O(L) 每字符串,L ≤ 50,極快。