📄 getline.html
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head> <meta name="generator" content= "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org"> <title>getline</title> <link href="../cppreference.css" rel="stylesheet" type="text/css"></head><body><table> <tr> <td> <div class="body-content"> <div class="header-box"> <a href="../index.html">cppreference.com</a> > <a href= "index.html">C++ Strings</a> > <a href= "getline.html">getline</a> </div> <div class="name-format"> getline </div> <div class="syntax-name-format"> Syntax: </div> <pre class="syntax-box"> #include <string> istream& getline( istream& is, string& s, char delimiter = '\n' );</pre> <p>The C++ string class defines the global function getline() to read strings from an I/O stream. The getline() function, which is not part of the string class, reads a line from <em>is</em> and stores it into <em>s</em>. If a character <em>delimiter</em> is specified, then getline() will use <em>delimiter</em> to decide when to stop reading data.</p> <p>For example, the following code reads a line of text from <strong>stdin</strong> and displays it to <strong>stdout</strong>:</p> <pre class="example-code"> string s; getline( cin, s ); cout << "You entered " << s << endl;</pre> <p>After getting a line of data in a string, you may find that <a href="../cppsstream/index.html">string streams</a> are useful in extracting data from that string. For example, the following code reads numbers from standard input, ignoring any "commented" lines that begin with double slashes:</p> <pre class="example-code"> // expects either space-delimited numbers or lines that start with // two forward slashes (//) string s; while( getline(cin,s) ) { if( s.size() >= 2 && s[0] == '/' && s[1] == '/' ) { cout << " ignoring comment: " << s << endl; } else { istringstream ss(s); double d; while( ss >> d ) { cout << " got a number: " << d << endl; } } }</pre> <p>When run with a user supplying input, the above code might produce this output:</p> <pre class="example-code"> // test ignoring comment: // test 23.3 -1 3.14159 got a number: 23.3 got a number: -1 got a number: 3.14159 // next batch ignoring comment: // next batch 1 2 3 4 5 got a number: 1 got a number: 2 got a number: 3 got a number: 4 got a number: 5 50 got a number: 50</pre> <div class="related-name-format"> Related topics: </div> <div class="related-content"> (C++ I/O) <a href="../cppio/get.html">get</a><br> (C++ I/O) <a href="../cppio/getline.html">getline</a><br> <a href="../cppsstream/index.html">string streams</a> </div> </div> </td> </tr> </table></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -