사용자가 다음과 같은 형식으로 내용을 입력하도록 요청하는 중입니다. 그런 다음 문자열에 "cd"를 저장하고 다른 문자열에 "directory"를 저장합니다.strncpy 함수가 제대로 작동하지 않습니다.
void main()
{
char buf[50], cdstr[2], dirstr[50];
printf("Enter something: ");
fgets(buf, sizeof(buf), stdin);
//store cd in cdstr
strncpy(cdstr, buf, 2);
printf("cdstr: %s(test chars)\n", cdstr);
//store directory in dirstr
strncpy(dirstr, buf+3, sizeof(buf)-3);
printf("dirstr: %s(test chars)\n", dirstr);
}
출력은 입력과 같습니다 : CD의 경로 이유
cdstr: cdcd pathname //incorrect answer
(test chars) //an extra "\n"
dirstr: pathname //correct answer
(test chars) //an extra "\n"
여기 내 코드는?
힌트 : buf''의 데이터 유형을 찾아서'버피 + 3'를 분석 할 수 있습니다. 또한,'strncpy()'를 사용할 때 null을 확인하십시오. –
'strncpy'는 복사 된 문자에 end-of-string 문자 ('\ 0')를 추가하지 않기 때문에 검사하십시오. 게다가'cdstr'에'\ 0'을위한 공간을 확보하지 않았습니다. –
여분의'\ n'은'fgets'가 항상'\ n'을 포착하기 때문입니다. 이것은 모두 일반적인 지식입니다. 'strncpy'와'fgets' 문서를 공부 해보십시오. –