C++ 알고리즘 기초2 -문자열에 특수문자 포함하기, 여러줄 출력, 정수 출력

1. 문자열에 특수문자 포함시키기

 

C++에서 문자열은 큰따옴표 "로 표현하는데, "와 같은 문자를 포함하는 문장을 출력하고 싶다면?

 

그냥 ""Hello""로 해버리면..

 

#include <iostream>
using namespace std;

int main() {
    cout << ""Hello"";

    return 0;
}

 

 

다음과 같이 에러남

 

다른 언어들처럼 특수문자 앞에 \을 붙여주면 가능

 

\을 붙여주면 해당 특수문자를 문자 그대로 인식해준다는 의미

 

#include <iostream>
using namespace std;

int main() {
    cout << "\"Hello\"";

    return 0;
}

 

He says "It's a really simple sentence".를 출력하는 프로그램을 작성해보면?

 

파이썬과는 다르게 작은따옴표 '는 문자열을 나타내는 친구로 쓸수 없으니.. 얘 앞에 \을 붙일필요는 없

 

#include <iostream>
using namespace std;

int main() {

    cout << "He says \"It's a really simple sentence\".";

    return 0;
}

 

 

2. 여러줄 출력

 

C++에서 줄바꿈은 cout << endl;을 사용한다

 

#include <iostream>
using namespace std;

int main() {

    cout << "Hello World";
    cout << endl;
    cout << "C++ is Fun";
    
    return 0;
}
Hello World
C++ is Fun

 

혹은 다른 언어들처럼 "\n"을 이용하여, cout << "\n";도 가능하다

 

#include <iostream>
using namespace std;

int main() {
    cout << "Hello World";
    cout << "\n";
    cout << "C++ is Fun";

    return 0;
}

Hello World
C++ is Fun

 

혹은 <<을 연속으로 사용하여 한줄로도 가능하다.

 

구체적으로 cout << "Hello World" << endl << "C++ is Fun";을 하면, 

 

cout 한번만 사용해서 두줄을 출력한다

 

#include <iostream>
using namespace std;

int main() {
    cout << "Hello World" << endl << "C++ is Fun";

    return 0;
}

Hello World
C++ is Fun

 

3. 숫자 출력

 

문자 출력만 얘기했는데 cout을 이용해 숫자도 출력 가능하다..

 

#include <iostream>
using namespace std;

int main() {
    
    cout << 3;
    
    return 0;
}

 

4. 공백을 두고 출력

 

2개의 값을 공백에 두고 출력하고 싶다면.. 두 값 사이에 " "을 넣어주면 된다

 

구체적으로 3과 5를 한줄에 공백을 두고 출력하고 싶다면?

 

cout << "3 5"하면 될 것

 

혹은 cout << 3 << " " << 5;도 가능하겠지?

 

#include <iostream>
using namespace std;

int main() {
    
    cout << "3 5";
    return 0;
}

 

 

5. 연습문제

 

Total days in Year

365

Circumference rate

3.1415926535

 

을 출력해본다면??

 

#include <iostream>
using namespace std;

int main() {
    
    cout << "Total days in Year" << endl << 365 << endl << "Circumference rate" << endl << "3.1415926535";
    return 0;
}

 

C++은 기본적으로 실수를 6자리만 출력해주나봐

 

그래서 3.1415926535는 문자열로 지정하면 그대로 출력해

TAGS.

Comments