[C]

ChanMin Jeon·2022년 6월 7일

Objective

In this challenge, we will learn some basic concepts of C that will get you started with the language. You will need to use the same syntax to read input and write output in many C challenges. As you work through these problems, review the code stubs to learn about reading from stdin and writing to stdout.

Task

This challenge requires you to print on a single line, and then print the already provided input string to stdout. If you are not familiar with C, you may want to read about the printf() command.

Example

The required output is:

Hello, World!
Life is beautiful
Function Descriptio

Complete the main() function below.

The main() function has the following input:

string s: a string
Prints

two strings: "Hello, World!" on one line and the input string on the next line.
Input Format

There is one line of text, .

Sample Input 0

Welcome to C programming.
Sample Output 0

Hello, World!
Welcome to C programming.

Solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() 
{
	
    char s[100];
    scanf("%[^\n]%*c", &s);
  	
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    printf("Hello, World!\n");
    printf("%s", s);
    return 0;
}

C언어에서는 문자열을 바로 입력받아서 저장할 수 있는 자료형이 없다.
예를 들어, string 타입의 변수를 선언할 수 없다는 말이다.

그래서 C언어는 문자열을 저장하기 위해 배열을 사용한다.
char 타입의 array 를 선언하여 입력한 문자열의 각 문자 하나하나를 배열의 요소로 넣는다.

하지만, 출력할 때는 %s 를 사용하여 문자열을 출력할 수 있다.
(%s 이런걸... 출력타입?? 아니면 출력 형식?? 이라고 했던 것 같다.)
%s 도 사용하지 않았더라면, char 타입의 배열을 반복문을 통해 각 요소마다 접근해서 출력을 해줘야하지 않을까 한다.

작성한 코드를 하나하나 살펴보면,

char 자료형(데이터타입)으로 s 라는 이름을 가진 변수를 선언.
scanf() 를 통해 표준 입력을 받는다.

printf() 함수로 출력하기 위한 문자열을 인수로 가질 수 있다.
변수를 사용하게 된다면,
출력형식 %s 를 사용하여 printf() 를 통해 출력한다.

%[^\n]%*c ??


Reference
HackerRank, "Hello world in C", https://www.hackerrank.com/challenges/hello-world-c/problem?isFullScreen=true, (2022.06.08)

profile
FunnyCoding

0개의 댓글