본문 바로가기
c++

1-2. 입력(cin), 공백으로 구분된 여러 숫자 입력

by yoonjunho 2023. 1. 15.

<공백으로 구분된 여러 개 숫자 입력>

3 4 2 12 6 8

이렇게 공백으로 구분된 숫자를 입력받을 때, 

1
2
3
4
5

이렇게 입력받을 때와 마찬가지로,

int n;
	cin >> n;
	vector <int> divisor;
	int natural_number;
	for (int i = 0; i < n; i++) {
		cin >> natural_number;
		divisor.push_back(natural_number);
	}

똑같은 반복문을 사용해도 똑같이 입력이 된다.

 

 

 

 

cin의 예시

#include <iostream>

int main(void) {
	using namespace std;
	int i;

	cout << "숫자를 입력하세여 : ";
	cin >> i;

	if (i < 0)
		cout << i<<"는 음수입니다. \n";
	else if (i > 0)
		cout << i<<"는 양수입니다. \n";
	else if (i == 0)
		cout << i<<"는 0입니다.\n";

	return 0;
}

============================================================================================

cin>>i; 

ㄴ namespace std에 정의되어있다. - cin은 console input이라는 뜻이다.

using namespace std

int i;

cin>>i;

이렇게 하면 정수형 변수 i에 정수를 콘솔창에서 입력받을 수 있다.

============================================================================================

cin의 반환 값 :

https://stackoverflow.com/questions/38978266/how-can-stdcin-return-a-bool-and-itself-at-the-same-time -> cin은 cin 객체를 반환하며, iostream 헤더파일 내에 이를 bool 또는 다른 타입으로 바꾸어 줄 수 있는 conversion operator가 정의되어 있다고 함.

if (std::cin >> value);
cin이 if나 while 안에 들어가면 예외적으로 operator에 의해 자동으로 bool로 바뀜.
예시 : 

	int integer = 1;
	if (cin >> integer) {
		cout << "입력 성공";
	}
	else {
		cout << "입력 실패";
	}


bool b = std::cin >> value;
: 하지만 일반적인 경우에는 형변환을 명시하지 않을 경우 operator가 실행되지 않음.

bool b = static_cast<bool>(std::cin >> value);
: 이때 위와 같이 변환을 명시해주면 잘 작동함

ㄴ출처 : https://skku.goorm.io/qna/4241

============================================================================================

cin배열문자열을 입력받을 때, 배열의 크기는 상관이 없다. 자동으로 알아서 다 된다.

	char str[3];

	while (cin>>str) {
		cout << str << endl;
	}

ㄴ에서 

이런식으로 길이 2이상의 문자열을 넣어도 자동으로 다 된다.

ㄴ(c에서는 %s을 이용하여 입력받을 때, 배열의 크기-1을 넘으면 입력을 못받았다. 

https://dojang.io/mod/page/view.php?id=336) 

============================================================================================

<<한 줄에 여러 개 입력>>

#include <iostream>
#include <stdio.h>
using namespace std;
int day = 0;
struct DAY {
int year;
int month;
int day;
};
int main(void){
DAY today;
DAY d_day;
cin >> today.year >> today.month >> today.day;
return 0;
}

 

이렇게 한 줄로 표준입력 할 수 있다. cin하나 쓰고 변수들을 >> 로 이어서 쓰면

'c++' 카테고리의 다른 글

5. [C++]while문  (0) 2023.01.15
4. [C++]for 반복문, 문자열(입력, 길이 등)  (0) 2023.01.15
3. switch-case문  (0) 2023.01.15
2. if문  (0) 2023.01.15
1. c++표준출력  (0) 2023.01.14