• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

1번문제 flag의 값이 1이 나오는 이유?

22.12.20 03:48 작성 22.12.20 03:49 수정 조회수 238

0

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

#define NLEN 30

struct name_count {
	char first[NLEN];
	char last[NLEN];
	int num;
};

void receive_input(struct name_count*);
void count_characters(struct name_count*);
void show_result(const struct name_count*);
char* s_gets(char* st, int n);

int main()
{
	struct name_count user_name;

	receive_input(&user_name);
	count_characters(&user_name);
	show_result(&user_name);

	return 0;
}

char* s_gets(char* st, int n)
{
	char* ret_val;
	char* find;

	ret_val = fgets(st, n, stdin);  // vs. scanf()
	if (ret_val)
	{
		find = strchr(st, '\n');	// look for newline
		if (find)					// if the address is not NULL
			*find = '\0';			// place a null character there
		else
			while (getchar() != '\n')
				continue;			// dispose of rest of line
	}

	return ret_val;
}

void receive_input(struct name_count* ptr_nc)
{
	int flag;

	printf("Input your first name:\n>> ");

	//s_gets(ptr_nc->first, NLEN);
	flag = scanf("%[^\n]%*c", ptr_nc->first); // ^ : cap operator:not을 의미합니다.
	printf("%d \n", flag);
	if (flag != 1)
		printf("Wrong input");

	printf("Input your last name:\n>> ");

	//s_gets(ptr_nc->last, NLEN);
	flag = scanf("%[^\n]%*c", ptr_nc->last);
	if (flag != 1)
		printf("Wrong input");
}

void count_characters(struct name_count* ptr_nc)
{
	ptr_nc->num = strlen(ptr_nc->first) + strlen(ptr_nc->last);
	//ptr_nc->num = (int)strlen(ptr_nc->first) + (int)strlen(ptr_nc->last); // int castings remove warnings
}

void show_result(const struct name_count* ptr_nc)
{
	printf("Hi, %s %s. Your name has %d characters.\n",
		ptr_nc->first, ptr_nc->last, ptr_nc->num);
}

 

위 코드에서 scanf 의 return이 flag인데 정상적으로 입력했을 때 1이 나오는 이유가 궁금합니다.

답변 1

답변을 작성해보세요.

0

강민철님의 프로필

강민철

2022.12.23

scanf가 무엇을 반환하는지 확인해보시면 이해에 도움이 될 듯 합니다

scanf는 포맷 형식에 알맞는 입력이 들어온 개수를 리턴합니다.

정상적으로 입력했을 때 얼마든지 1이 나올 수 있지요.

이인교님의 프로필

이인교

질문자

2022.12.24

scanf format이 다음과 같은데, 이것도 1개로 처리하는 것인가요? 단순한 format specifier과 달라서 헷갈리네요. %s 처럼 문자열 1개로 처리하는게 맞을까요?

%[^\n]%*c