std::getline
來自 cppreference.com
< cpp | string | basic_string
定義於標頭檔案 <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
從輸入流中讀取字元並將它們放入字串中
1) 呼叫 str.erase()。
2) 從 input 提取字元並附加到 str,直到發生以下情況之一(按列出的順序檢查):
b) 下一個可用的輸入字元是 delim(透過 Traits::eq(c, delim) 測試),在這種情況下,從 input 提取分隔符字元,但不附加到 str。
3,4) 與 getline(input, str, input.widen('\n')) 相同,即預設分隔符是換行符。
目錄 |
[編輯] 引數
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() { // 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\n"; // use separator to read parts of the line 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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 91 | C++98 | getline 不作為非格式化輸入函式 |
作為非格式化輸入函式 |
[編輯] 參見
提取字元直到找到給定字元 ( std::basic_istream<CharT,Traits> 的公共成員函式) |