용량과 안전한 서식 지정
Coddy의 C++ 개발자를 위한 C 코스 레슨. 48개 중 29번째.
C++ 문자열의 크기 증가는 소유자가 용량을 관리합니다. C 형식 지정에서는 호출자가 쓰기 가능한 저장 공간과 용량을 제공해야 합니다. 문자열 객체에 대한 가정을 일반 char 포인터에 적용하지 마세요.
쓰기 가능한 포인터만으로는 용량을 알 수 없습니다. 용량을 전달하고 snprintf의 결과를 확인해 잘림이 발생했는지 확인하세요.
C++ 예제
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>
int main(){
std::string out="Hi,";out+="Ada";std::cout<<out<<"\n";
}
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를 반환하고 버퍼는 변경하지 마세요. 드라이버는 용량 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 컴파일러