인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

인프런 커뮤니티 질문&답변

픽린님의 프로필 이미지
픽린

작성한 질문수

홍정모의 따라하며 배우는 C언어

11.5 문자열을 출력하는 다양한 방법들

(11:00) 코드를 실행했을 때 이상한 결과가 막 출력됩니다.

작성

·

341

0

11.5강의 11:00부분입니다.

void custom_put(const char* str); //Only two lines

int custom_put2(const char* str); //Add \n, return # of characters

int main()

{
/*

Custom function

*/

custom_put("Just ");

custom_put("Do it!");

printf("%d\n", custom_put2("12345"));

return 0;

}

void custom_put(const char* str)

{

while (*str != '\n') //while(*str)

putchar(*str++);

}

int custom_put2(const char* str)

{

int count = 0;

while (*str)

{

putchar(*str++);

count++;

}

putchar('\n');

return count;

}


교수님께서 작성하셨던 코드 그대로 다 입력을 했습니다.
빌드를 실행하면 정상적으로 빌드가 되는데, 콘솔창에서 정말 이상한 값들만 자동으로 쫙 출력됩니다.

이게 어떤 원인때문에, 이렇게 발생한 문제인지 알고 싶습니다.

답변 1

0

안녕하세요,

첨부하신 코드에 오타가 보입니다.

void custom_put(const char* str)
{
	while (*str != '\n') 
		putchar(*str++);
}

 

가 아닌

void custom_put(const char* str)
{
	while (*str != '\0') //while(*str)
		putchar(*str++);
}

 

입니다.

*str이 줄바꿈(\n)을 할 때까지 읽는 것이 아니라 문자열의 끝을 나타내는 \0까지 읽어들이는 것입니다.

줄바꿈할 때까지 putchar를 호출했기에 쓰레기값들이 출력된 것입니다.

픽린님의 프로필 이미지
픽린

작성한 질문수

질문하기