elesis's haunt
[C++] iostream 입출력 (cout, cin, endl) 본문
iostream 라이브러리를 사용해 콘솔에 텍스트를 입출력 받을 수 있습니다.
- cout : 출력
- << (출력 연산자)를 사용해 같은행에 둘 이상의 값을 출력할 수 있습니다.
#include <iostream>
int main() {
std::cout << "Hello world!";
return 0;
}
// Hello world!
#include <iostream>
int main() {
std::cout << "Hello";
std::cout << "world!";
return 0;
}
// Hello world!
- cin : 입력
#include <iostream>
int main() {
std::cout << "insert number 'x' : ";
int x; // 값을 덮어 쓸 것이기 때문에 굳이 변수 x를 초기화할 필요가 없습니다.
std::cin >> x; // 입력값을 변수 x에 할당합니다.
std::cout << "'x' : " << x << std::endl;
return 0;
}
// insert number 'x' : 1(입력값)
// 'x' : 1
- endl : 줄바꿈
#include <iostream>
int main() {
std::cout << "Hello!" << std::endl;
std::cout << "C++!";
return 0;
}
// Hello!
// C++!
제가 보고 있는 책에는 using namespace std;를 사용해서 std::cout를 cout로 바로 사용합니다.
#include <iostream>
using namespace std;
int main() {
cout << "Hello world!";
return 0;
}
// Hello world!
그러나 이는 권장되는 사항이 아닙니다.
- global로 namespace를 선언한다면 namespace에 선언된 함수나 다른 요소들의 이름이 겹칠 수 있기 때문에 뜻하지 않았던 오류를 발생시킬 수 있기 때문입니다.
using namespace foo;
using namespace bar;
int main() {
Blah(); // foo에만 있는 함수 --- (O)
Quux(); // bar에만 있는 함수 --- (O)
FooBar(); // foo, bar 둘 다에 들어있는 동명이인의 함수 --- (X) 오류 발생
return 0;
}
출처: https://boycoding.tistory.com/137 해당글을 요약했습니다.
https://sexycoder.tistory.com/16 해당글을 참조했습니다.
Comments