문자열입력받고, 문자,단어개수,열개수 출력하기

신동원·2021년 9월 19일
0

C

목록 보기
1/10
#include<stdio.h>
#include<limits.h>
#include<stdlib.h>
#include <float.h>
#include <stdbool.h>
#include <complex.h>
#include <string.h>
#include <math.h>
#include<stdbool.h>
#include<ctype.h>
#define STOP '.'

int main()
{
char c;
int n_chars = 0;
int n_lines = 1;
int n_words = 1;
bool word_flag = false;
bool word_flag1 = false;
printf("Enter text:\n");
while ((c = getchar()) != STOP) {

	if (c == '\n')
		n_lines++;
	if (isspace(c))
		word_flag = true;
	if (word_flag && !isspace(c) && word_flag1)
	{
		n_words++;
		word_flag = false;
		word_flag1 = false;
	}
	if (!isspace(c))
	{
		n_chars++;
		word_flag1 = true;
	}
}

if (n_chars == 0) {
	n_words = 0;
}

printf("Characters = %d, Words = %d, Lines = %d\n", n_chars, n_words, n_lines);
return 0;
}

문자열을 입력하면 문자,단어,열의 개수를 출력해주는 프로그램이다.
getchar()를 통해 문자열을 입력받으면 STOP(.) 마침표를 만날 때까지 무한루프를 돌게 된다.


if (c == '\n')
n_lines++;
줄바꿈을 만나게 되면 열의 개수를 +1해주고,


if (isspace(c))
word_flag = true;
띄어쓰기를 만나게 되면 word_flag를 true로 바꿔준다. (띄어쓰기를 몇번 입력하고 단어를 쓸지 모르기때문에 깃발역할을 해주는 변수 word_flag를 만들어 활용한다.)


if (word_flag && !isspace(c) && word_flag1)
{
n_words++;
word_flag = false;
word_flag1 = false;
}
띄어쓰기가 아니고 word_flag와 word_flag1이 true일 때 단어를 +1해주고 word_flag와 word_flag1를 false로 다시 바꿔준다. word_flag는 띄어쓰기를 해야 true가 되고 word_flag1은 줄바꿈이나 문자를 적어야 true가 된다. 즉 띄어쓰기를 하고 줄바꿈이나 문자를 입력하여야 단어가 +1된다.


if (!isspace(c))
{
n_chars++;
word_flag1 = true;
}
입력 받은 문자가 띄어쓰기가 아닐경우 문자를 +1씩 계속해주고 word_flag1을 true로 바꿔준다.


if (n_chars == 0) {
n_words = 0;
}
int n_words의 초기값이 1이기 때문에 아무것도 입력하지 않고 마침표만 입력하여 종료하였을 때 단어의 개수를 0으로 바꿔준다.



결과창



줄바꿈을 했을 경우



아무것도 입력하지 않고 끝냈을 경우

profile
오늘보다 내일 더 나은 사람이 되기 위해 노력하자

0개의 댓글