zoukankan      html  css  js  c++  java
  • getline

    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;;
    }
  • 相关阅读:
    面试题 01.04. 回文排列
    面试题 01.03. URL化
    面试题 01.02. 判定是否互为字符重排
    面试题 01.01. 判定字符是否唯一
    剑指 Offer 68
    剑指 Offer 68
    Wpf杀死所有线程、Wpf关闭程序杀死所有线程
    wpf的webbrowser与javascript交互
    WPF将HHMMSS转换为时间格式字符串
    IDEA建立Spring MVC Hello World 详细入门教程
  • 原文地址:https://www.cnblogs.com/freewater/p/2892818.html
Copyright © 2011-2022 走看看