C/C++中,2个getline函数使用

 C函数库中:

stdio.h

/* Like `getdelim', but reads up to a newline.

   This function is not part of POSIX and therefore no official
   cancellation point.  But due to similarity with an POSIX interface
   or due to the implementation it is a cancellation point and
   therefore not marked with __THROW.  */
extern _IO_ssize_t getline (char **__restrict __lineptr,
       size_t *__restrict __n,
       FILE *__restrict __stream) __wur;

该函数,用于读取文件。

 

C++函数库中:

iostream

 

/**
       *  @brief  String extraction.
       *  @param  s  A character array in which to store the data.
       *  @param  n  Maximum number of characters to extract.
       *  @return  *this
       *
       *  Returns @c getline(s,n,widen('\n')).
      */
      inline __istream_type&
      getline(char_type* __s, streamsize __n)
      { return this->getline(__s, __n, this->widen('\n')); }

 

__istream_type&
      getline(char_type* __s, streamsize __n, char_type __delim);

 

对比实例:

 

/* 
 * File:   main2.cpp
 * Author: Vicky
 *
 * Created on 2011年11月25日, 上午10:16
 */

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <stdlib.h>

/*
 * 
 */
int main(void) {
    std::cout << "both getline the different !" << std::endl;

    int ret;
    FILE* pf;
    pf = fopen("./main.cpp", "r");
    if (pf == NULL) {
        perror("can not open file './main.cpp'");
        return 1;
    }

    size_t size;
    ssize_t read;
    char* line;
    line = (char*) malloc(64); // 如果分配太小的话,会出错
    // 这个是stdio的getline
    while ((read = getline(&line,&size,pf)) != EOF) {
        std::cout << line << std::endl;
    }
    line = NULL;

    
    std::cout << "inter something ,‘exit’!" << std::endl;
    
    std::string str;
    while (std::getline(std::cin,str) && str != "exit") {
        std::cout << ">>" << str << std::endl;
    }


    ret = fclose(pf);
    if (ret != 0) {
        perror("can not close file './main.cpp'");
        return 1;
    }
    return 0;
}


     输出结果:

 

both getline the different !
/* 

 * File:   main.cpp

 * Author: Vicky

 *

 * Created on 2011年11月25日, 上午10:12

 */



#include <iostream>

#include <cstring>



/*

 * 

 */

int main(void) {

    std::string str;

    while (std::cin >> str && str != "exit") {

        std::cout << str << std::endl;

    }

    return 0;

}



inter something ,‘exit’!
hello
>>hello
I'm vicky
>>I'm vicky
who are you?
>>who are you?
goodbye
>>goodbye
exit

运行成功(总计时间: 29s)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值