名前空間
変種
操作

std::getline

提供: cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
ヘッダ <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 );
(1)
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 );
(1) (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 );
(2)
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 );
(2) (C++11以上)

getline は入力ストリームから文字を読み込み、それを文字列に格納します。

1) UnformattedInputFunction として動作しますが、 input.gcount() は影響されません。 sentry オブジェクトの構築および確認の後、以下のことを行います。
1) str.erase() を呼びます。
2) 以下のいずれかが発生するまで (上から順に確認されます)、 input から文字を抽出し、それを str に追加します。
a) input の end-of-file 状態。 この場合、 getlineeofbit を設定します。
b) 次の利用可能な文字が delim である。 判定は Traits::eq(c, delim) によって行われます。 この場合、区切り文字は input から抽出されますが、 str には追加されません。
c) str.max_size() 個の文字が格納された。 この場合、 getlinefailbit を設定し��リターンします。
3) いかなる理由においても、1文字も (破棄される区切り文字さえも) 抽出されなかった場合、 getlinefailbit を設定してリターンします。
2) getline(input, str, input.widen('\n')) と同じです。 つまり、デフォルトの区切り文字は改行です。

目次

[編集] 引数

input - データを取得するストリーム
str - データを格納する文字列
delim - 区切り文字

[編集] 戻り値

input

[編集] ノート

ホワイトスペース区切りの入力を消費するとき (int n; std::cin >> n; など)、後続のあらゆるホワイトスペース (改行を含みます) は、入力ストリームに残されます。 そのあと行指向の入力に切り替えたとき、 getline で取得される最初の行はそのホワイトスペースだけになるでしょう。 この動作が望ましくない場合は、例えば以下のような解決方法があります。

[編集]

以下の例はユーザの入力を読み込むために getline 関数を使う方法およびファイルを行単位で処理する方法をデモンストレーションします。

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

出力例:

What is your name? John Q. Public
Hello John Q. Public, nice to meet you.
 
The sum is 28

[編集] 関連項目

指定された文字が見つかるまで文字を抽出します
(std::basic_istream<CharT,Traits>のパブリックメンバ関数) [edit]