#include <stdio.h>
int main()
{
char str[50] = "", tmp[50] = "";
char *from, *to;
// 문자열 입력
printf("문자열을 입력하세요(50자 이내): ");
fgets(str, sizeof(str), stdin);
// str에 저장할 거고, size는 sizeof(str)만큼만 받아올거고, stdin(키보드에서)
// 문자열 복사
from = str;
to = tmp;
while (*from != '\\0') // '\\0'이 나올 때까지 반복
{
*to = *from; // 값을 복사
from++;
to++;
}
*to = '\\0'; // 문자열 끝에 널 문자를 추가 while에서 제외되니까!!
// 수정하지 말 것
printf("str: %stmp: %s", str, tmp);
return 0;
}
fgets() 동작:
sizeof(str) - 1
문자를 읽어옵니다.\\0
(문자열 종료 문자)을 자동으로 추가합니다.배열 상태:
str = "Hello, World!\\n\\0"
#include <stdio.h>
#define SIZE 5
void print_array(const int arr[], int *count)
{
int i;
printf("원소 출력: ");
for (i = 0; i < *count; i++)
printf("%d ", arr[i]);
printf("\\n");
}
int add_to_multiset(int arr[], int size, int value, int *count)
{
if (*count >= size) // 배열이 꽉 찬 경우 추가하지 않음
return 0;
arr[*count] = value; // 배열에 원소 추가
(*count)++; // 원소 개수 증가
return 1;
}
int main(void)
{
int arr[SIZE] = { 0 };
int cnt = 0;
while (cnt < SIZE)
{
int value;
// 배열에 추가할 원소 입력하기
printf("원소를 입력하세요: ");
scanf("%d", &value);
// 원소 출력
if (add_to_multiset(arr, SIZE, value, &cnt) == 0)
continue;
print_array(arr, &cnt); // print_array 함수 호출
}
return 0;
}
#include <stdio.h>
#define SIZE 5
void print_array(const int arr[], int *count)
{
int i;
printf("원소 출력: ");
for (i = 0; i < *count; i++)
printf("%d ", arr[i]);
printf("\\n");
}
int find_array(const int arr[], int size, int key)
{
for (int i = 0; i < size; i++)
{
if (arr[i] == key) //하나씩 돌아가면서 확인
{
printf("해당 원소가 이미 존재합니다.\\n");
return 1; // key가 배열에 존재할 경우 1 반환
}
}
return 0; // key가 배열에 존재하지 않으면 0 반환
}
int add_to_set(int arr[], int size, int value, int *count)
{
if (find_array(arr, *count, value) == 1)
return 0; // 배열에 이미 값이 있으면 추가하지 않음
if (*count >= size)
return 0; // 배열이 가득 찬 경우 추가하지 않음
arr[*count] = value; // 배열에 값 추가
(*count)++; // 원소 개수 증가
return 1;
}
int main(void)
{
int arr[SIZE] = { 0 };
int cnt = 0;
while (cnt < SIZE)
{
int value;
// 배열에 추가할 원소 입력하기
printf("원소를 입력하세요: ");
scanf("%d", &value);
if (add_to_set(arr, SIZE, value, &cnt) == 0)
continue;
print_array(arr, &cnt); // print_array 함수 호출
}
return 0;
}