Cpp, string 헤더에 선언되어 있는 getline 함수
std::getline - cppreference.com
std::getline - cppreference.com
template< class CharT, class Traits, class Allocator > std::basic_istream & getline( std::basic_istream & input, std::basic_string & str,
en.cppreference.com
오버로딩 함수들
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, std::basic_string<CharT,Traits,Allocator>& str, CharT delim );
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, std::basic_string<CharT,Traits,Allocator>& str, CharT delim );
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, std::basic_string<CharT,Traits,Allocator>& str);
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, std::basic_string<CharT,Traits,Allocator>& str);
기능
getline은 input stream에서 문자들을 읽고 그들을 string에 저장한다.
1) input.gcount()가 영향을 받지 않는 경우를 제외하고, UnformattedInputFunction처럼 동작한다. sentry 객체를 구성하고 검증한 이후, 다음과 같이 동작한다.:
1) str.erase()를 호출한다
2) 다음 상황이 발생하기 전까지 input에서 문자들을 추출하고 그들을 str에 덧붙인다.
a) end-of-file 조건이 input에 있을 때. 이 경우 getline은 eofbit를 설정한다.
b) 다음 접근가능한 input 문자가 구분자 일때(Traits::eq(c, delim)에 의해 확인한다).이 경우 구분 문자는 input에서 추출 되지만 str에는 덧붙여지지 않는다.
c) str.max_size()개의 문자들이 저장 되었을 때. 이 경우 getline은 failbit를 설정하고 반환한다.
3) 만약 어떠한 이유로든 어떤한 문자들이라도 추출되지 않는다면(심지어 버려진 구분자 조차), getline은 failbit를 설정하고 리턴한다.
2) getline(input, str, input.widen('\n'))과 같이 default 구분자는 endline 문자이다.
Parameters
input - 데이터를 얻을 스트림
str - 데이터를 넣을 스트링
delim - 구분 문자
Return value
input
별첨
공백으로 구분된 input을 사용할 때, 개행 문자를 포함 하여 뒤에 오는 모든 공백은 stream에 남는다.
그런 다음 line-oriented input으로 전향할 때(직전에 얘기한 공백 구분자 input), getline으로 검색된 첫줄은 그 공백이 될 것이다. 이런 원지 않은 상황이 발생할 때, 긍정적인 해결 방법은 다음을 포함한다:
- getline을 한번 호출하여(일종의 초기 호출) 공백 줄을 버리는 용으로 사용
- std::cin>>std::ws를 사용해 연이은 공백 제거.
- cin.ignore(std::numeric_limits<std::streamsize>:: max(),'\n');을 활용하여 input의 모든 나머지 문자들 무시.
예제
#include <string>
#include <iostream>
#include <sstream>
int main()
{
// greet the user
std::string name;
std::cout << "What is your name? ";
std::getline(std::cin, name);
std::cout << "Hello " << name << ", nice to meet you.\n";
// read file line by line
std::istringstream input;
input.str("1\n2\n3\n4\n5\n6\n7\n");
int sum = 0;
for (std::string line; std::getline(input, line); ) {
sum += std::stoi(line);
}
std::cout << "\nThe sum is: " << sum << "\n\n";
// use separator to read parts of the line
std::istringstream input2;
input2.str("a;b;c;d");
for (std::string line; std::getline(input2, line, ';'); ) {
std::cout << line << '\n';
}
}