끄적끄적 개발공부

# C++ 기초 입출력

HYuk 2021. 4. 7. 02:42
728x90

# 소수점 출력 관련

cout.precision(자리수);

cout<<fixed;

하고 출력하면 원하는 만큼 소수점 자리수를 출력 할 수 있다.

#include <iostream>

using namespace std;

int main()
{
	cout.precision(6);
	cout << fixed;
	float x;
	cin >> x;
	cout << x;
}

-> 입력 받은 숫자를 소수점 6자리까지 출력

 

# 입력 받은 숫자의 자리수를 고정하고 '0'을 출력시키는 방법

cout.width(자리수);

cout.fill('0');

하고 출력하면 원하는 자리수를 출력해주고 빈칸은 '0'으로 채워진다

ex) 87 입력 시 -> 0087 로 출력

 

#include <iostream>

using namespace std;

int main()
{
	int iYear = 0, iMonth = 0, iDay = 0;
	char chDot;
	cin >> iYear >> chDot >> iMonth >> chDot >> iDay;

	cout.width(4);
	cout.fill('0');
	cout << iYear << chDot;

	cout.width(2);
	cout.fill('0');
	cout << iMonth << chDot;

	cout.width(2);
	cout.fill('0');
	cout << iDay;
}

-> 년, 월, 일 을 입력후 빈칸은 0으로 채운다

999.1.31 입력 시 -> 0999.01.31 출력

 

 

# 배열에서 빈칸까지 모두 입력 받는 방법

cin.getline(변수, 크기);

#include <iostream>

using namespace std;

int main()
{
	char chData[2000];
	cin.getline(chData, 2000);
	cout << chData;
}

-> Programming is fun! (빈칸) 입력시 그대로 똑같이 출력

 

728x90