std:: getline
|
ヘッダーで定義
<string>
|
||
|
template
<
class
CharT,
class
Traits,
class
Allocator
>
std::
basic_istream
<
CharT, Traits
>
&
|
(1) | |
|
template
<
class
CharT,
class
Traits,
class
Allocator
>
std::
basic_istream
<
CharT, Traits
>
&
|
(2) | (C++11以降) |
|
template
<
class
CharT,
class
Traits,
class
Allocator
>
std::
basic_istream
<
CharT, Traits
>
&
|
(3) | |
|
template
<
class
CharT,
class
Traits,
class
Allocator
>
std::
basic_istream
<
CharT, Traits
>
&
|
(4) | (C++11以降) |
getline
は入力ストリームから文字を読み取り、それらを文字列に格納します:
目次 |
パラメータ
| input | - | データを取得するストリーム |
| str | - | データを格納する文字列 |
| delim | - | 区切り文字 |
戻り値
input
注記
空白文字で区切られた入力(例:
int
n
;
std::
cin
>>
n
;
)を読み込む場合、後続の空白文字(改行文字を含む)は入力ストリームに残されます。その後、行指向の入力に切り替えた場合、
getline
で取得される最初の行はその空白文字だけになります。この動作が望ましくない場合、考えられる解決策には以下があります:
-
明示的な冗長な初期呼び出し
getline。 - 連続する空白文字の削除 std:: cin >> std:: ws による。
- 入力行の残存文字の無視 cin. ignore ( std:: numeric_limits < std:: streamsize > :: max ( ) , ' \n ' ) ; による。
例
以下の例は、
getline
関数を使用してユーザー入力を読み取り、ストリームを行単位で処理する方法、または
delim
パラメータを使用して行の一部を処理する方法を示しています。
#include <iostream> #include <sstream> #include <string> int main() { // ユーザーへの挨拶 std::string name; std::cout << "What is your name? "; std::getline(std::cin, name); std::cout << "Hello " << name << ", nice to meet you.\n"; // ファイルを行単位で読み取り 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"; // セパレータを使用して行の一部を読み取り std::istringstream input2; input2.str("a;b;c;d"); for (std::string line; std::getline(input2, line, ';');) std::cout << line << '\n'; }
出力例:
What is your name? John Q. Public Hello John Q. Public, nice to meet you. The sum is 28. a b c d
不具合報告
以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。
| DR | 適用対象 | 公開時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 91 | C++98 |
getline
は非書式化入力関数として動作していなかった
|
非書式化入力関数として動作する |
関連項目
|
指定された文字が見つかるまで文字を抽出する
(
std::basic_istream<CharT,Traits>
の公開メンバー関数)
|