用戶輸入長度 n,動態分配字符數組,讀取字符串並驗證長度是否超標。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int n;
printf("請輸入最大長度:");
scanf("%d", &n);
getchar(); // 吸收換行
char *p = (char *)malloc(n + 1); // +1 存 \0
if (!p) { perror("malloc"); return 1; }
printf("請輸入字符串:");
fgets(p, n + 1, stdin); // 安全讀取,含換行
p[strcspn(p, "\n")] = '\0'; // 去掉換行
if (strlen(p) > n) {
printf("長度超標!實際:%zu,限制:%d\n", strlen(p), n);
} else {
printf("合法:%s\n", p);
}
free(p);
return 0;
}
#include <iostream>
#include <string>
int main() {
size_t n;
std::cin >> n;
std::cin.ignore();
std::string s;
std::getline(std::cin, s);
if (s.length() > n) std::cout << "超標\n";
else std::cout << s << '\n';
return 0;
}