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)


展开阅读全文

没有更多推荐了,返回首页