모두의 코드
C++ 레퍼런스 - string 의 getline 함수

작성일 : 2020-07-17 이 글은 48975 번 읽혔습니다.

아직 C++ 에 친숙하지 않다면 씹어먹는 C++ 은 어때요?

getline

<string> 에 정의됨

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);
// C++ 11 에 추가됨
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);
// C++ 11 에 추가됨

getline 함수는 입력 스트림에서 문자들을 읽어서, 인자로 받은 문자열에 저장합니다.

입력 스트림에서 문자를 읽다가 delim 문자를 읽게되면, 해당 문자를 버리고, 읽어들이기를 종료합니다. 만약에 delim 문자를 설정하지 않았다면, 디폴트로 개행 문자('\n')로 설정됩니다.

또한, 어떠한 연유에서든지 읽기 오류가 발생한다면, failbit 를 설정하며 오류를 발생시킵니다.

만약에, 입력 스트림에서 읽다가 끝에 End-Of-File 에 도달하였다면, eofbit 를 설정하며 읽기를 중지합니다.

참고로, 입력받는 문자는 push_back 함수를 통해 문자열 뒤에 게속 덧붙여집니다. 따라서, 만약에 읽어들일 문자열의 길이를 대충 알고 있다면, 그 크기를 reserve 해 놓는 것이 좋습니다.

한 가지 주의할 사항은, 입력 방식 중에 공백문자를 스트림에 남겨놓는 입력방식 뒤에 getline 을 바로 호출하게 된다면, getline 은 해당 공백문자를 읽고 바로 읽기를 종료하게 됩니다.

예를 들어서 int n; std::cin >> n; 을 하게 된다면, operator>> 가 스트림에서 숫자를 읽고 뒤에 오는 공백문자를 스트림에 남겨 놓게 됩니다. 따라서 그 다음 바로 getline 을 호출하게 되면, 그 공백문자를 읽고 바로 읽기를 끝내겠지요. 이와 같은 상황을 막기 위해서는 스트림에서 남아 있는 공백문자들을 모두 지워줘야 하는데,

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

를 통해 간단히 수행할 수 있습니다.

인자

  • input - 문자들을 읽어들일 스트림

  • str - 입력할 문자를 저장할 문자열

  • delim - 구분 문자 (이 문자가 나타나기 전 까지 읽어들인다.)

리턴값

입력 받은 문자열을 리턴한다.

예시

#include <iostream>
#include <sstream>
#include <string>

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";

  // stringstream 은 마치 문자열을 입력 스트림으로 생각하게 해줍니다.
  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";
}

실행 결과

실행 결과

What is your name? John Q. Public
Hello John Q. Public, nice to meet you.
 
The sum is 28
첫 댓글을 달아주세요!
프로필 사진 없음
강좌에 관련 없이 궁금한 내용은 여기를 사용해주세요

    댓글을 불러오는 중입니다..