[ getline 함수 동작 ]
1. 개행문자('\n')를 만날 때까지 입력 스트림에서 문자들을 읽는다.
2. 개행문자를 읽지만, 이를 결과 문자열에 저장하지 않는다.
3. 개행문자는 입력 스트림에서 제거된다. (즉, 버퍼에 남지 않음).
4. 결과 문자열에는 개행문자 직전까지의 문자들만 저장된다.
*** cin 은 공백을 무시하지만 버퍼에 남기기 때문에
int num;
cin >> num;
와 같이 getline 사용하기 전에 cin을 썼다면
cin.ignore(), cin.get() 와 같은 함수를 사용하면 된다.
*** 모든 입력을 'getline()' 으로 받고
필요시 형변환하는 것도 하나의 방법이다.
string input;
getline(cin, input);
num = stoi(input); // string to int
getline(cin, str);
# getline 함수 모음
std::getline (C++ 표준 라이브러리) :
string 객체 사용
*** 공백 포함 가능 / 기본적으로 개행 문자('\n')까지 읽음 / 지정 구분자 읽기 가능
#include <string>
istream& getline (istream& is, string& str, char delim);
istream& getline (istream& is, string& str);
---------------------------------------------------------
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
cout << "Enter a line of text: ";
getline(cin, line);
cout << "You entered: " << line << endl;
return 0;
}
---------------------------------------------------------
string line;
getline(cin, line); // 개행 문자까지 공백 포함하여 읽음
getline(cin, line, ','); // 쉼표까지 공백 포함하여 읽음
std::cin.getline (C++ 표준 입력 스트림) :
char 배열 사용
*** 공백 포함 가능, 기본적으로 개행 문자('\n')까지 읽을 수 있음
#include <iostream>
istream& getline (char* s, streamsize n);
istream& getline (char* s, streamsize n, char delim);
------------------------------------------------------
#include <iostream>
using namespace std;
int main() {
char name[50];
cout << "Enter your name: ";
cin.getline(name, 50);
cout << "Hello, " << name << "!" << endl;
return 0;
}
------------------------------------------------------
char name[50];
cin.getline(name, 50); // 개행 문자까지 공백 포함하여 읽음
cin.getline(name, 50, ','); // 쉼표까지 공백 포함하여 읽음
ifstream::getline (파일 입력 스트림) :
파일에서 한 줄씩 읽을 때 사용
*** 공백 포함 가능, 기본적으로 개행 문자('\n')까지 읽음, 지정 구분자 읽기 가능
#include <fstream>
ifstream& getline (char* s, streamsize n);
ifstream& getline (char* s, streamsize n, char delim);
-------------------------------------------------------
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("example.txt");
char buffer[100];
if (file.is_open()) {
while (file.getline(buffer, 100)) {
cout << buffer << endl;
}
file.close();
}
return 0;
}
-------------------------------------------------------
ifstream file("example.txt");
char buffer[100];
file.getline(buffer, 100); // 개행 문자까지 공백 포함하여 읽음
stringstream::getline (문자열 스트림) :
문자열을 특정 구분자로 나눌 때 사용
#include <sstream>
stringstream& getline (string& str, char delim);
stringstream& getline (string& str);
--------------------------------------------------
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main() {
string input = "apple,banana,cherry";
stringstream ss(input);
string item;
while(getline(ss, item, ',')) {
cout << item << endl;
}
return 0;
}