std::getline
ヘッダ <string> で定義
|
||
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, |
(1) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, |
(1) | (C++11以上) |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, |
(2) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, |
(2) | (C++11以上) |
getline
は入力ストリームから文字を読み込み、それを文字列に格納します。
input
から文字を抽出し、それを str
に追加します。delim
である。 判定は Traits::eq(c, delim) によって行われます。 この場合、区切り文字は input
から抽出されますが、 str
には追加されません。目次 |
[編集] 引数
input | - | データを取得するストリーム |
str | - | データを格納する文字列 |
delim | - | 区切り文字 |
[編集] 戻り値
input
。
[編集] ノート
ホワイトスペース区切りの入力を消費するとき (int n; std::cin >> n; など)、後続のあらゆるホワイトスペース (改行を含みます) は、入力ストリームに残されます。 そのあと行指向の入力に切り替えたとき、 getline
で取得される最初の行はそのホワイトスペースだけになるでしょう。 この動作が望ましくない場合は、例えば以下のような解決方法があります。
-
getline
を1回多く余計に呼ぶ。 - std::cin >> std::ws で連続するホワイトスペースを取り除く。
- cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); でその行の残りの文字をすべて無視する。
[編集] 例
以下の例はユーザの入力を読み込むために 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> のパブリックメンバ関数)
|