一、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 << "!\n"; }
執行結果:
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 << "!\n"; }
輸出結果:
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的為#鍵時,循環才會結束