Linux/Raspberry Pi
longest.c
값진
2021. 3. 16. 12:35
키보드 입력을 받아 입력된 문장 중에서 가장 긴 문장을 longest 배열에 복사하고, ^D를 입력하면 입력된 문장 중에서 가장 긴 문장을 프린트하고 종료하는 프로그램
- gets : \n이 입력되기 전까지의 문자열을 char형태로 저장해주는 함수(문자열을 입력받는 함수)
#include <stdio.h>
#include <string.h>
#define MAXLINE 100
void copy(char from[], char to[]);
char line[MAXLINE]; //입력된 줄
char longest[MAXLINE]; //가장 긴 줄
int main()
{
int len;
int max;
max=0;
while(gets(line) != NULL) {
len = strlen(line);
if (len > max) {
max = len;
copy(line, longest); ///어렵다
}
}
if(max > 0)
printf("%s",longest);
return 0;
}
/*copy: from을 to에 복사; to가 충분히 크다고 가정*/
void copy(char from[], char to[])
{
int i;
i = 0;
while((to[i]=from[i]) != '\0')
++i;
}