getline函数的一些问题

来源:互联网 发布:windows截图快捷键 编辑:程序博客网 时间:2024/06/15 14:43

getline()的原型是istream& getline ( istream &is , string &str , char delim );

其中 istream &is 表示一个输入流,譬如cin;      string&str表示把从输入流读入的字符串存放在这个字符串中(可以自己随便命名,str什么的都可以);char delim表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为'\n',也就是回车换行符(遇到回车停止读入)
如:
string line;cout << "please cin a line:"getline(cin, line, '#');cout << endl << "The line you give is:"line;
1.那么当输入"You are the #best!" 的时候,输入流实际上只读入了"You are the ",#后面的并没有存放到line中。然后程序运行结果应该是这样的:

please cin a line:You are the #best!
The line you give is:You are the 

而且这里把终止符设为#,你输入的时候就算输入几个回车换行也没关系,输入流照样会读入,譬如
please cin a line:You are the best!
//这里输入了一个回车换行
Thank you!
# //终止读入

The line you give is:You are the best!
//换行照样读入并且输出
Thank you!

以上就是getline()函数一个小小的实例了。

2.那么如果把getline()作为while的判断语句会怎么样呢?

让我们一起来分析一下while(getline(cin,line))语句

注意这里默认回车符停止读入,按Ctrl+Z或键入EOF回车即可退出循环。

在这个语句中,首先getline从标准输入设备上读入字符,然后返回给输入流cin,注意了,是cin,所以while判断语句的真实判断对象是cin,也就是判断当前是否存在有效的输入流。所以这种情况下不管你怎么输入都跳不出循环,因为你的输入流有效,跳不出循环。

然而如果误以为while判断语句的判断对象是line(也就是line是否为空),然后想通过直接回车(即输入一个空的line)跳出循环,却发现怎么也跳不出循环。这是因为你的回车只会终止getline()函数的读入操作。getline()函数终止后又进行while()判断(即判断输入流是否有效,你的输入流当然有效,满足条件),所以又运行getline()函数。

C++中本质上有两种getline函数:

一种在头文件<istream>中,是istream类的成员函数

一种在头文件<string>中,是普通函数。

在<istream>中的getline函数有两种重载形式:

istream& getline (char* s, streamsize n );istream& getline (char* s, streamsize n, char delim );

作用是从istream中读取至多n个字符保存在s对应的数组中。即使还没读够n个字符,如果遇到换行符'\n'(第一种形式)或delim(第二种形式),则读取终止,'\n'或delim都不会被保存进s对应的数组中。

#include <iostream>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;}

在<string>中的getline函数有四种重载形式:

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

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

istream& getline (istream&  is, string& str);

istream& getline (istream&& is, string& str);

用法和上一种类似,不过要读取的istream是作为参数is传进函数的。读取的字符串保存在string类型的str中。

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


原创粉丝点击