std::getline
提供: cppreference.com
<tbody>
</tbody>
| ヘッダ <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)
str.erase() を呼びます。2) 以下のいずれかが発生するまで (上から順に確認されます)、
input から文字を抽出し、それを str に追加します。b) 次の利用可能な文字が
delim である。 判定は Traits::eq(c, delim) によって行われます。 この場合、区切り文字は input から抽出されますが、 str には追加されません。2)
getline(input, str, input.widen('\n')) と同じです。 つまり、デフォルトの区切り文字は改行です。引数
| 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 関数を使う方法およびファイルを行単位で処理する方法をデモンストレーションします。
Run this code
#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>のパブリックメンバ関数)
|