• 2.C++标准库函数:getline函数 定界流输入截取函数 windows编程


    引言:今天工作遇到了一个需要按行读取txt文件数据的需求,查询了一下getline()函数,发现这竟然是一个C++的标准库函数,而且设计的很好,特地做一下记录。getline本质是一个定界流输入截取函数,默认是换行符‘/n’

    个人技术博客(文章整理+源码): https://zobolblog.github.io/LearnWinAPI/

    最终效果:

     

     

     

    1.getline函数声明

    getline函数实际上是在两个模块都有实现,一个是string一个是istream,它们的用处都是一样的,只是输入的参数不太一样。一个是char*一个是string。

    std::istream::getline:
    
    istream& getline (char* s, streamsize n );
    
    istream& getline (char* s, streamsize n, char delim );
    
    std::getline (string):
    
    istream& getline (istream& is, string& str);
    
    istream& getline (istream& is, string& str, char delim);

    2.使用方法:

    第一个std::istream::getline的使用,就是cin或者ifstream,调用成员函数的形式,cin.getline:

    第1个参数s是承接的字符数组,大小必须大于等于获得的数据长度。

    第2个参数n,是s的最大长度,因为char*是得不到数组长度的,必须额外给出,防止内存访问越界、

    char name[256];
    
    std::cin.getline(name, 256);

    第二个std::getline (string),类似公共函数了,流的输入也放到了参数列表中,因为string内部有动态长度设计,就不用额外给出了。

    std::getline (std::cin,name);

    char delim就是定界符号,默认是‘/n’换行符,也可以自己指定。getline会返回从起始,到定界符前的数据(不包括定界符本身,但流会经过定界符,相当于光标跳到定界符后面)。

     

    3.官方网址:

    国内的搜索档案实在是太乱了,起始官方讲的很好:

    https://cplusplus.com/reference/istream/istream/getline/

    https://cplusplus.com/reference/string/string/getline/

     

    源码:

     

    #include <iostream>
    
    int main() {
    
    char name[256], title[256],web[256];
    
    std::cout << "Please, enter your name: ";
    
    std::cin.getline(name, 256);
    
    std::cout << "Please, enter your tutorial : ";
    
    std::cin.getline(title, 256);
    
    std::cout << "Please, enter your tutorial : ";
    
    std::cin.getline(web, 256);
    
    std::cout << name << "'s tutorial is " << title << "'s web is ";
    
    return 0;
    
    }

     

    效果:

     

    本人个人技术博客: https://zobolblog.github.io/LearnWinAPI/ ,个人公众号:zobol的魔法藏书室,windows编程技术讨论群:811851762。所有源码和文章均整理上传其中,欢迎关注。

  • 相关阅读:
    北京理工大学复试上机--2014
    北京理工大学复试上机--2013
    北京理工大学复试上机--2012
    北京理工大学复试上机--2011
    北京理工大学复试上机--2010
    Python的逻辑结构和函数
    Python的概述
    BOM
    正则表达式的匹配
    jQuery的插件和跨域、ajax
  • 原文地址:https://www.cnblogs.com/zobol/p/16387176.html
Copyright © 2020-2023  润新知