용량과 안전한 서식 지정
Coddy의 C# 개발자를 위한 C 코스 레슨. 48개 중 29번째.
C#에서 문자열을 구성할 때는 대상 저장 공간을 관리합니다. C에서 서식 지정에는 종료 문자를 포함한 명시적인 용량이 필요하며, snprintf는 버퍼를 자동으로 늘리는 대신 잘림을 알릴 수 있습니다.
쓰기 가능한 포인터만으로는 용량을 알 수 없습니다. 용량을 전달하고 잘림 여부를 확인하려면 snprintf의 결과를 검사하세요.
C# 예제
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {
static void Main(){
Console.WriteLine("Hi,"+"Ada");
}
}
C# 출력:
Hi,AdaC 예제
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
int main(void) {
char out[16];snprintf(out,sizeof out,"Hi,%s","Ada");puts(out);
return 0;
}
C 출력:
Hi,Ada챌린지
쉬움입력은 128바이트보다 짧은 ASCII 이름 하나입니다. greeting(name,out,capacity)를 구현하세요. 전체 결과와 종단 문자가 들어갈 공간이 충분한 경우에만 Hi,와 이름을 쓰세요. 실패하면 false를 반환하고 버퍼를 변경하지 마세요. 드라이버는 capacity 8을 사용하고 결과 또는 too-long를 출력합니다.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 공개된 잠금 상태의 main.c에서 함수를 직접 호출하므로, 선언된 공개 API와 호환되도록 유지하세요. 또 다른 main을 추가하지 마세요. 작업에서 범위를 명시적으로 확인하지 않는 한 모든 숫자 작업 테스트 데이터는 오버플로를 방지할 만큼 작은 값입니다. 지정된 출력만 출력하세요. 입력 파싱과 출력 예시가 제시된 경우 드라이버가 이를 처리합니다.
직접 해보기
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){char text[128]="";if(fgets(text,sizeof text,stdin))text[strcspn(text,"\n")]=0;char out[8]="keep";if(greeting(text,out,sizeof out))puts(out);else {if(strcmp(out,"keep")!=0)return 2;puts("too-long");};return 0;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C# 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러