Menu
CoddyTech

파싱과 검증

Coddy의 C++ 개발자를 위한 Dart 코스 레슨. 48개 중 24번째.

C++ std::from_chars는 결과의 errc를 통해 실패를 알리고 출력 인수에 값을 씁니다. std::stoi는 대신 std::invalid_argument를 던지며, 둘 다 숫자 접두부를 허용하므로 std::stoi("12px")는 12를 반환합니다. Dart tryParse는 파싱된 nullable 값을 직접 반환하며, 두 Dart 파서는 모두 뒤에 오는 텍스트를 거부합니다.

int.tryParse는 실패 시 null을 반환하지만, int.parse는 FormatException을 던집니다. 엄격한 비즈니스 문법에서는 변환 전에 구문을 검사하고 변환 후에 별도로 범위를 검사해야 할 수 있습니다.

완전한 C++ 프로그램:

#include <charconv>
#include <iostream>
#include <string>
int main(){std::string s="nope";int n=0;auto r=std::from_chars(s.data(),s.data()+s.size(),n);std::cout<<(r.ec==std::errc{}?std::to_string(n):"invalid")<<"\n";std::cout<<std::stoi("42")<<"\n";}

완전한 Dart 프로그램:

void main(){print(int.tryParse('nope')??'invalid');print(int.tryParse('42'));}
challenge icon

챌린지

쉬움

bounded(String text)를 구현하세요. 앞뒤 공백을 제거하고 10진 부호 있는 정수를 파싱하세요. 입력이 유효하지 않거나 값이 -50부터 50 사이를 벗어나면 null을 반환하세요. 입력에는 줄바꿈이 없습니다. 값 또는 invalid를 출력하세요. 10진수 입력에는 선택적 부호와 ASCII 숫자만 사용하며, 16진수 표기는 사용할 수 없습니다.

편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart는 입력을 파싱하고 출력을 반환하며, 잠긴 드라이버는 공개 API를 별도로 검사하고 결과를 줄바꿈 하나와 함께 출력합니다.

코드는 functions.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.

직접 해보기

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(bounded(' +7 ')==7 && bounded('7x')==null && bounded('-51')==null);
stdout.writeln(solve(input));
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 Dart의 모든 레슨

직접 연습해 보세요: 온라인 Dart 컴파일러