1cfd3bbb56
Topic_CSS/Topic_HTML/Topic_JavaScript/Topic_Prompt/Topic_Comfyui 등 기존 카테고리 폴더를 정리하고, Topic_Graphic/Dev 등 신규 산출물과 Topics 내부 세션/메모리 기록을 동기화.
4.2 KiB
4.2 KiB
id, title, category, status, verification_status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, created_at, updated_at, review_reason, merge_history, tags, raw_sources, applied_in, github_commit
| id | title | category | status | verification_status | canonical_id | aliases | duplicate_of | source_trust_level | confidence_score | created_at | updated_at | review_reason | merge_history | tags | raw_sources | applied_in | github_commit | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| c-input-validation | C Input Validation | Programming_Language | draft | conceptual |
|
B | 0.86 | 2026-07-04 | 2026-07-04 |
|
|
C Input Validation
🎯 한 줄 통찰 (One-line insight)
The integer-validation example doesn't use scanf() directly to detect bad input — it reads the RAW LINE with fgets() first, then tries to parse it with sscanf() and checks whether that parse SUCCEEDED (== 1), meaning robust validation in C separates "getting text from the user" from "trying to interpret that text as a number," rather than trusting scanf()'s own format-matching to gracefully reject non-numeric input. [S1]
🧠 핵심 개념 (Core concepts)
- Range validation via a do-while loop — repeatedly prompt until the entered value falls within an allowed range;
while (getchar() != '\n');clears any leftover characters in the input buffer afterscanf(). [S1] - Empty-text validation — read with
fgets(), strip the trailing newline (name[strcspn(name, "\n")] = 0;), then loop while the resulting string length is 0. [S1] - Integer-format validation — read the raw line as a STRING via
fgets(), then attemptsscanf(input, "%d", &number); if it returns1(one successful conversion), the input was a valid integer — otherwise, prompt again. [S1] - Buffer-clearing necessity — leftover characters (like an unconsumed newline) in the input stream after
scanf()can silently corrupt the NEXT read unless explicitly cleared. [S1]
📖 세부 내용 (Details)
- Range-bounded input with buffer clearing:
do { printf("Choose a number between 1 and 5: "); scanf("%d", &number); while (getchar() != '\n'); } while (number < 1 || number > 5);. [S1] - Rejecting empty text input:
do { fgets(name, sizeof(name), stdin); name[strcspn(name, "\n")] = 0; } while (strlen(name) == 0);. [S1] - Validating that input is actually an integer via sscanf's return value:
while (fgets(input, sizeof(input), stdin)) { if (sscanf(input, "%d", &number) == 1) { break; } else { printf("Invalid input. Try again: "); } }. [S1]
⚖️ 모순 및 업데이트 (Contradictions & updates)
- 문자열로 먼저 읽고 sscanf로 파싱을 검증하는 전략: scanf()로 직접 숫자를 받는 대신 fgets()로 원문을 통째로 받은 뒤 sscanf()의 반환값(성공한 변환 개수)을 확인하는 방식이 잘못된 입력을 더 안전하게 걸러낸다는 점이 확인됨. [S1]
🛠️ 적용 사례 (Applied in summary)
1~5 범위의 숫자 선택, 빈 이름 거부, 문자가 아닌 정수만 허용하는 세 가지 검증 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
💻 코드 패턴 (Code patterns)
Validating that user input is actually an integer using fgets() + sscanf()'s return value (C):
int number;
char input[100];
printf("Enter a number: ");
while (fgets(input, sizeof(input), stdin)) {
if (sscanf(input, "%d", &number) == 1) {
break; // valid integer
} else {
printf("Invalid input. Try again: ");
}
}
✅ 검증 상태 및 신뢰도
- 상태: draft
- 검증 단계: conceptual
- 출처 신뢰도: B (W3Schools — widely used educational reference, not a primary standards body)
- 신뢰 점수: 0.86
- 중복 검사 결과: 신규 생성 (New discovery)
🔗 지식 그래프 (Knowledge Graph)
- 상위/루트: C Tutorial
- 관련 개념: C Error Handling, C User Input, C Debugging
- 참조 맥락: 입력 검증 — 디버깅(Debugging) 챕터로 이어짐.
📚 출처 (Sources)
- [S1] W3Schools — C Input Validation — https://www.w3schools.com/c/c_input_validation.php
📝 변경 이력 (Change history)
- 2026-07-04: Initial draft synthesized from the W3Schools "C Input Validation" page (Astra wiki-curation, P-Reinforce v3.1 format).