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:

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

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


执行结果:

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

 

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

 

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

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

}


输出结果:

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是结束标志,默认为换行符

例子:

 

#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;

}

 

输出结果:

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的为#键时,循环才会结束

原文地址:https://www.cnblogs.com/aprincess/p/11626376.html