域名已备案,为方便访问,测试阶段使用IP访问的页面,避免更换服务器导致不可访问,可将IP更换为域名:onlymhy.top
已复制到剪贴板!
C++ getline()和get()的区别 | 寒 雨
0%

C++ getline()和get()的区别

最近在看《C++ Primer Plus 第6版 中文版》,有些问题发现又忘记了所以就单独将问题记录下来。


getline()和get()都是面向行的输入。
文中代码来自于书中代码或者基于书中代码修改

getline()

get()函数读取整行,通过判断输入的换行符来确定结尾,并将换行符丢弃(从输入流中舍弃),在结尾使用空字符代替换行符。此函数有两个参数,第一个参数用来存储输入行的数组的名称,第二个参数是尧都区的字符数。如果第二个参数是20,则函数最多读取19个字符,剩下的数组空间则存储自动在结尾处添加的空字符。所以,geiline()函数在读取指定数目的字符或遇到换行符时停止读取。下面是书中示例代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// instr2.cpp -- reading more than one word with getline
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];

cout << "Enter your name:\n";
cin.getline(name, ArSize); // reads through newline
cout << "Enter your favorite dessert:\n";
cin.getline(dessert, ArSize);
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
return 0;
}

下面是程序输出

1
2
3
4
5
Enter your name:
Dirk Hammernose
Enter your favorite dessert:
Radish Torte
I have some delicious Radish Torte for you, Dirk Hammernose.

可以看出完整将一行输入进行读取。

get()

这个函数的工作方式与getline()类似,接受的参数相同,解释参数的方式也相同,并且都是读取到行尾。但get并不在读取并丢弃换行符,而是将其留在输入队列中。
如果上面getline()示例代码一样,在输入“Dirk Hammernose”回车后会由于换行符还在输入队列中,第二次调用get时,由于首先读取的字符是换行符,判断为行尾,所以不会发现任何可读的内容。例如下面代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// instr3.cpp -- reading more than one word with get() & get()
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];

cout << "Enter your name:\n";
// cin.get(name, ArSize).get(); // read string, newline
cin.get(name, ArSize);
// cout << (int)name[3] << endl;
cout << "Enter your favorite dessert:\n";
cin.get(dessert, ArSize).get();
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
cin.get();
return 0;
}

上述代码结果如下。

1
2
3
4
Enter your name:
Dirk Hammernose
Enter your favorite dessert:
I have some delicious for you, Dirk Hammernose.

当第一次调用get(),输入“Dirk Hammernose”按下回车后,输入队列是“Dirk Hammernose\n”,将Dirk Hammernose存储在name数组中,输入队列还有“\n”。在第二次调用get()时,首先读取的是换行符”\n”,get()认为已经是行尾了,从而没发现任何可以读取的内容。
不过,get()有另外一种变体。使用不带任何参数的cin.get()调用可读取下一个字符,包括换行符,因此可以用来处理换行符,因此在两次调用get()中间可以插入

1
cin.get(); 

还有是使用get的方式将两个类成员函数拼接,如下所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// instr3.cpp -- reading more than one word with get() & get()
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];

cout << "Enter your name:\n";
cin.get(name, ArSize).get(); // read string, newline
cout << "Enter your favorite dessert:\n";
cin.get(dessert, ArSize).get();
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
return 0;
}

可以这样用是因为cin.get(name, ArSize)返回的是一个cin对象,随后该对象被用来调用get()函数。cin.getline()相同。

-------------本文结束感谢您的阅读-------------
学习分享,感谢支持。(可选)
  • 本文作者: 思寒忆雨
  • 本文链接: http://onlymhy.top/c-1/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

欢迎关注我的其它发布渠道