getline is to read a line of characters from input stream.
My naive implement as follows,
1 #include<stdio.h> 2 3 /* getline: get line into s, return length. 4 arguments: lim is the max length of s. 5 */ 6 int getline(char s[],int lim) 7 { 8 int c;//store character acquired from input stream. 9 int i=0;//index of s. 10 while(--lim > 0 && (c=getchar())!=EOF && c!='\n') 11 { 12 s[i++]=c; 13 } 14 if(c=='\n') 15 s[i++]=c; 16 s[i]='\0'; 17 return i; 18 }
This function is very simple, but simple doesn't indicate no bugs. When the length of characters inputed exceeds lim which is the argument of getline, getline returns wrong result. This bug can be solved by using automatic incremental string variable instead the character array.
the Standard Template Library (STL) class in Visual C++.
template<class _E, class _TYPE, class _A> inline basic_istream<_E, _TYPE>& getline( basic_istream<_E, _TYPE>& Istream, basic_string<_E, _TYPE, _A>& Xstring, const _E _D=_TYPE::newline( ) );
The getline function creates a string containing all of the characters from the input stream until one of the following situations occurs: - End of file. - The delimiter is encountered. - is.max_str elements have been extracted.
Example:
// string_getline_sample.cpp // compile with: /EHsc // Illustrates how to use the getline function to read a // line of text from the keyboard. // // Functions: // // getline Returns a string from the input stream. ////////////////////////////////////////////////////////////////////// #pragma warning(disable:4786) #include <string> #include <iostream> using namespace std ; int main() { string s1; cout << "Enter a sentence (use <space> as the delimiter): "; getline(cin,s1, ' '); cout << "You entered: " << s1 << endl;; }