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;;
    }
  • 相关阅读:
    C#+ArcEngine10.0+SP5实现鼠标移动动态显示要素属性信息
    C#中实现excel文件批量导入access数据表中
    C#子窗体闪烁问题解决
    C#打印代码运行时间
    TableLayoutPanel导致的闪屏问题
    线段余弦角+凸包算法
    ICommand相关知识
    批量导出access某表内容到word文档
    通过数组里的时间重新排序数组
    数组层级叠加
  • 原文地址:https://www.cnblogs.com/freewater/p/2892818.html
Copyright © 2011-2022 走看看