문자열 데이터 std::string
- string클래스의 인스턴스이다. 그러므로 #include <string> 을 선언해줘야한다.
- char배열과 달리 문자열의 최대 길이를 고려할 필요가 없어 사용하기 편리하다. ( ↔ char name[30])
- 코드 중간 아무 곳에서나 변수를 선언할 수 있다.
std::string으로 문자열 출력해보기
#include <iostream>
#include <string>
int main(){
std::string myStr = "Hello world";
std::cout << myStr;
}
입력받아서 문자열 출력해보기
#include <iostream>
#include <string>
int main(){
std::string strName;
std::cin >> strName; //길이 제한 없이 입력을 받는다.
std::cout << strName;
}
std:: 없이 사용하기 (using 사용)
#include <iostream>
#include <string>
//std:: 사용하지 않아도 되도록 using 사용
using std::string;
using std::cin;
using std::cout;
int main(){
string strName = "hello world";
cin >> strName;
cout << strName;
}
std:: 없이 사용하기 (using namespace 사용)
#include <iostream>
#include <string>
using namespace std; //std 전체를 std::없이 사용할 수 있도록 한다.
int main(){
string strName = "hello world";
cin >> strName;
cout << strName;
}
C++ 개념 더보기
'◼️C++' 카테고리의 다른 글
[C++] 변수 선언 및 정의 (0) | 2023.08.31 |
---|---|
[C++] 자료형 (0) | 2023.08.31 |
[C++] Visual Studio 에서 추가로 사용하는 헤더파일 <stdafx.h> (0) | 2023.08.31 |
[C++] 여러 변수 출력하기 (0) | 2023.08.31 |
[C++] Hello world 출력해보기 (0) | 2023.08.31 |