zoukankan      html  css  js  c++  java
  • getline函数

    读取输入的一行数据,遇到回车符 停止。

    • 标准C中没有getline函数,gcc编译器中加入了getline函数,
    #include <stdio.h>
      ssize_t getline(char **lineptr, size_t *n, FILE *stream);

    其中*lineptr指向一个动态分配的内存区域。*n是所分配内存的长度。如果*lineptr是NULL的话,getline函数会自动进行动态内存的分配(忽略*n的大小),所以使用这个函数非常注意的就使用要注意自己进行内存的释放。
    如果*lineptr分配了内存,但在使用过程中发现所分配的内存不足的话,getline函数会调用realloc函数来重新进行内存的分配,同时更新*lineptr和*n。
    注意*lineptr指向的是一个动态分配的内存,由malloc,calloc或realloc分配的,不能是静态分配的数组。

    • C++在标准库中添加了getline函数,对不同的输入流对象都定义了一个getline函数。

      

    std::fstream::getline
    std::istream::getline
    std::ifstream::getline
    std::iostream::getline
    std::wfstream::getline
    std::wistream::getline
    std::wifstream::getline
    std::wiostream::getline
    std::stringstream::getline
    std::basic_fstream::getline
    std::basic_istream::getline
    std::istringstream::getline
    std::wstringstream::getline
    std::basic_ifstream::getline
    std::basic_iostream::getline
    std::wistringstream::getline
    std::basic_stringstream::getline
    std::basic_istringstream::getline

    在头文件<iostream>中声明了getline函数:

    istream::getline
    istream& getline (char* s, streamsize n );
    istream& getline (char* s, streamsize n, char delim ); 

    delim参数是指定分隔符。如果不指定的话,默认使用' '

    void test1(){
        char line[100];
        while(cin.getline(line,100))
            cout<<line<<endl;
    }

    C++中还定义了一个在std名字空间的全局函数,因为这个getline函数的参数使用了string字符串,所以声明在了<string>头文件中了。

    istream& getline ( istream& is, string& str, char delim );
    istream& getline ( istream& is, string& str );
    void test2(){
        string line;
        while(getline(cin,line))
            cout<<line<<endl;
    }

    所以在C++中读取一行的函数是不读入换行符的,而GCC中getline函数是读入换行符的。

  • 相关阅读:
    一个简单的knockout.js 和easyui的绑定
    knockoutjs + easyui.treegrid 可编辑的自定义绑定插件
    Knockout自定义绑定my97datepicker
    去除小数后多余的0
    Windows Azure Web Site (15) 取消Azure Web Site默认的IIS ARR
    Azure ARM (1) UI初探
    Azure Redis Cache (3) 创建和使用P级别的Redis Cache
    Windows Azure HandBook (7) 基于Azure Web App的企业官网改造
    Windows Azure Storage (23) 计算Azure VHD实际使用容量
    Windows Azure Virtual Network (11) 创建VNet-to-VNet的连接
  • 原文地址:https://www.cnblogs.com/LUO77/p/5763788.html
Copyright © 2011-2022 走看看