Files
2nd/10_Wiki/Topic_Programming/Topic_C/C_Input_Validation.md
T
Antigravity Agent e9cbf23ab5 docs(10_Wiki): Dev 폴더 누락분 반영 — Topic_Programming으로 통합
이전 재구성 작업에서 Dev/ 폴더가 누락되었던 것을 반영.

- Dev/Topic_Programming(중첩 폴더, 78개)은 Dev 자체 최상위 폴더들
  (Architecture/Conventions/Engineering_Intelligence 등)과 완전 중복이라 제거.
- Dev 최상위 엔지니어링 지식 폴더(Architecture/Conventions/Engineering_Intelligence/
  Failure_Library/Generalized_Principles/Language/Pattern_Catalog/Platform_Guides/
  Subsystems, 77개)는 이미 Topic_Programming/Topic_Programming에 더 최신 버전이
  존재해 중복 제거(고유 콘텐츠 1개는 예외 처리하여 이동 보존).
- Dev의 W3Schools 언어 튜토리얼 폴더(Topic_C/CPP/CSS/CSharp/HOWTO/HTML/Java/
  JavaScript/PHP/Python/SQL/W3CSS, 1201개)는 전부 Topic_Programming 하위로 이동.
- 에이전트 운영 상태(.astra/docs)는 그대로 유지, 콘텐츠 폴더만 정리.
- Topic_Programming 최종 문서 수: 2784 → 3985.
2026-07-05 00:39:13 +09:00

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
validate number range
sscanf validation
C 입력 검증
B 0.86 2026-07-04 2026-07-04
c
programming-language
w3schools
input-validation
scanf
sscanf
https://www.w3schools.com/c/c_input_validation.php

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 after scanf(). [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 attempt sscanf(input, "%d", &number); if it returns 1 (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)

📚 출처 (Sources)

📝 변경 이력 (Change history)

  • 2026-07-04: Initial draft synthesized from the W3Schools "C Input Validation" page (Astra wiki-curation, P-Reinforce v3.1 format).