(一)C中的getline()
1、标准C中没有定义getline()函数。
《c程序设计语言》中的getline()的一种实现
int getline(char s[],int lim)//lim为限制的字符串长度
{
int c,i;//c定义为int类型的原因:足够大可以存放EOF
for(i=0;i<lim-1&&(c=getchar())!='\n'&&c!=EOF;++i)
s[i]=c;
if('\n'==c)
{
s[i++]='\n';//c++中的getline函数实现不包含'\n'
}
s[i]='\0';
return i;
}
2、在gcc编译器中,对标准库进行了扩展,加入了一个getline函数
#include <stdio.h>
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
其中*lineptr指向一个动态分配的内存区域(由malloc,calloc或realloc分配的,不能是静态分配的数组)。
*n是所分配内存的长度。如果*lineptr是NULL的话,getline函数会自动进行动态内存的分配(忽略*n的大小)
如果*lineptr分配了内存,但在使用过程中发现所分配的内存不足的话,getline函数会调用realloc函数来重新进行内存的分配,同时更新*lineptr和*n。
注意:最后要进行内存的释放: free(lineptr);
使用示例:
(1)没有提前动态分配内存
#include <stdio.h>
int main()
{
char *line=NULL;
char length=0;
while(getline(&line,&length,stdin)>0)
printf("%d %s\n",length,line);
free(line);
return 0;
}
CentOS中 输入1 :abcd ef
输出1:120 abcd ef
输入2:abc 输出2: 120 abc
(2)提前动态分配了内存
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *line=(char*)malloc(10);
char length=5;
while(getline(&line,&length,stdin)>0)//getline()读入的包括最后的换行符
printf("%d %s\n",length,line);
free(line);
return 0;
}
CentOS中 输入1 :abc 输出1:5 abc
输入2:abcdef 输出2:10 abcdef (输入长度大于length,小于分配的内存时,length等于分配的内存大小)
输入3:abcdefghijk 输出3: 13 abcdefghijk (输入长度大于分配的内存时会进行realloc(),length为输入的字符数+2(‘\n’与‘\0’)
(二)C++中的getline()
1、getline function(string::getline())是定义在std命名空间的全局函数,但是因为函数里面使用了string所以声明在了<string>头文件中
函数原型 :
istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );
char delim 为结束符,默认的是换行符:'\n'
CSDN中示例:
#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;;
}
2、getline method
c++对不同的流对象都声明了getline方法
(1)标准输入流std::istream::getline()
在<iostream>中声明的原型:
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
CSDN中示例:
#include <iostream>
using namespace std;
int main( )
{
char c[10];
cin.getline( &c[0], 5, '2' );//以'2'作为结束符
cout << c << endl;
}
(2)文件流:std::fstream::getline()
示例:
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
fstream fs("fstream.txt", ios::in | ios::out | ios::trunc);
if (!fs.bad())
{
// Write to the file.
fs << "Writing to a basic_fstream object..." << endl;
fs << "getline() test line!"<<endl;
fs.close();
// Dump the contents of the file to cout.
char s[50];
fs.open("fstream.txt", ios::in);
while(fs.getline (s,50))
{
cout<<s<<endl;
}
fs.close();
}
}
(三)参考资料:
2、CSDN