자료구조
자료구조 제 3강
한 면만 쓴 종이
2022. 1. 9. 23:10
연습문제 풀이

/*
* 2022-01-23
* 연습문제 1
* 프로그램을 실행하면 $와 한 칸의 공백문자를 출력하고 사용자의 입력을 기다린다.
* 문장을 입력하면 문장 그대로와 길이를 출력한다.
*/
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 40
int read_line(char str[], int n);
int main_1(void) {
char buffer[BUFFER_SIZE];
while (1) {
printf("$ ");
int len = read_line(buffer, BUFFER_SIZE);
//fgets(buffer, BUFFER_SIZE, stdin);
//buffer[strlen(buffer) - 1] = '\0'; //buffer의 마지막 문자가 줄바꿈 문자가 되지 않도록 하기 위함
printf("%s : %d\n", buffer, len);
}
return 0;
}
int read_line(char str[], int n) {
int ch, i = 0;
while ((ch = getchar()) != '\n') //getchar의 리턴 타입은 int임 -> ch의 타입을 int로 함
if (i < n)
str[i++] = ch;
str[i] = '\0';
return i;
}

/*
* 2022-01-23
* 연습문제 2
* 프로그램을 실행하면 $와 한 칸의 공백문자를 출력하고 사용자의 입력을 기다린다.
* 문장을 입력하면 문장 그대로와 길이를 출력한다.
* 문장의 앞과 뒤에 붙은 공백문자들은 제거하고, 단어 사이에 두 개 이상의 연속된 공백문자들은 하나의 공백문자로 대체한다.
*/
#include <stdio.h>
#include <ctype.h> //white space 문자인지 검사하는 isspace함수 제공
#define BUFFER_SIZE 80
int read_line_with_compression(char compressed[], int limit);
int main() {
char line[BUFFER_SIZE];
while (1) {
printf("$ ");
int len = read_line_with_compression(line, BUFFER_SIZE);
printf("%s:%d\n", line, len);
}
return 0;
}
int read_line_with_compression(char compressed[], int limit)
{
int ch, i = 0;
while ((ch = getchar()) != '\n') {
if (i < limit - 1 && (!isspace(ch) || i > 0 && !isspace(compressed[i - 1])))
compressed[i++] = ch;
}
if (i > 0 && isspace(compressed[i - 1]))
i--;
compressed[i] = '\0';
return i;
}