getline()

遇到了要输入一行字符串的操作,我想除了fgets()的方法(fgets()用法链接),getline()也是可以的,但是我对getline的操作不熟悉,便查阅了很多资料,发现都说的很模糊,借这个机会我想彻底理清楚getline的用法;

    网上有说getline有两种用法的,我在这总结一下,

一、getline()用的比较多的用法
 

1)
istream& getline (istream& is, string& str, char delim);
(2)
istream& getline (istream& is, string& str);
 

//如果在使用getline()之前有使用scanf()那么需要用getchar()将前面的换行符读取,再使用getline(),这是我在编程时遇到的,希望大家重视一下
头文件#include<string>

is是一个流,例如cin

str是一个string类型的引用,读入的字符串将直接保存在str里面

delim是结束标志,默认为换行符

例子1:

// extract to string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string name;

cout << "Please, enter your full name: ";
getline (cin,name);
cout << "Hello, " << name << "!\n";

return 0;
}
执行结果:

Please, enter your full name: yyc yyc
Hello, yyc yyc!

总结;可以看出来,getline()这个函数是可以读取空格,遇到换行符或者EOF结束,但是不读取换行符的,这与fgets()存在着差异
例子2:

// extract to string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string name;

cout << "Please, enter your full name: ";
getline (cin,name,'#');
cout << "Hello, " << name << "!\n";

return 0;
}
输出结果:

Please, enter your full name: yyc#yyc
Hello, yyc!

总结可以看出,当我以#作为结束符时,#以及#后面的字符就不再读取。
 

二、cin.getline()用法
istream&getline(char * s,streamsize n);
istream&getline(char * s,streamsize n,char delim);


头文件#include<iostream>

s是一个字符数组,例如char name[100]

n是要读取的字符个数

delim是结束标志,默认为换行符

例子:

//istream::getline example
#include <iostream> // std::cin, std::cout
using namespace std;
int main () {
char name[256], title[256];

cout << "Please, enter your name: ";
cin.getline (name,256);

cout << "Please, enter your favourite movie: ";
cin.getline (title,256);

cout << name << "'s favourite movie is " << title;

return 0;
}
 

输出结果:

Please, enter your name: yyc
Please, enter your favourite movie: car
yyc's favourite movie is car

总结:可以看出,cin.getline()是将字符串存储在字符数组当中,也可以读取空格,也可以自己设置结束符标志
------------------------------------------------------------------------------------------------------------------------------------------------------------------

在日常使用中我们经常需要将getline与while结合使用
例1:
string str;
    while(getline(cin,str)){
        。。。
    }

那么在这个例子中是不是我们输入了一个回车就会跳出循环呢,答案是否定的,while只会检测cin的输入是否合法,那么什么时候会跳出循环呢,只有1.输入EOF,2.输入到了文件末尾

例2:
    string str;
    while(getline(cin,str),str != "#"){
       。。。
    }

在这个例子中,逗号运算符的作用就是将最后一个式子作为判定的条件,即while判断的是str != "#"这个条件,只有当输入到str的为#键时,循环才会结束
————————————————
版权声明:本文为CSDN博主「这个年纪的_我」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_37616927/article/details/86749099

猜你喜欢

转载自www.cnblogs.com/aprincess/p/11626376.html