get(char&) 和 get()
简介:
代码:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
/*
get(char&) 将输入的字符赋给其参数(不会跳过空字符————空格、制表符、换行符)
*/
char c1, c2, c3;
cin.get(c1).get(c2).get(c3);
cout << c1 << c2 << c3 << endl; //可以拼接使用
/*
get(void) 将输入字符转换为整型(通常是int)
注意:get(void)的返回值不是cin,而是int,因此不能拼接使用
*/
int i;
i = cin.get();
cout << i << endl;
i = cin.get(c1).get(c2).get(c3).get(); //valid get()虽然不能拼接使用,但是它可以放在最后
cout << c1 << c2 << c3 << i << endl;
cout << EOF;
return 0;
}
输出:
ABCDEFGH
ABC
68
EFG72
-1
getline()和get()
- istream & get(char *, int, char);
- istream & get(char *, int);
- istream & getline(char *, int, char);
- istream & getline(char *, int);
两者的区别:get()将分界字符留在输入队列中,而getline()不保留
代码:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
const int Limit = 255;
char input[Limit];
cout << "Enter a string for getline() processing:\n";
cin.getline(input, Limit, '#');
cout << "Here is your input:\n";
cout << input << "\nDone with phase 1\n";
char ch;
cin.get(ch);
cout << "The next input character is " << ch << endl;//getline()函数将丢弃输入中的分界字符#
if (ch != '\n')
// 读取并丢弃接下来的Limit个字符或直到到达第一个换行符
// 默认参数(1,EOF)
cin.ignore(Limit, '\n');
cout << "Enter a string for get() processing:\n";
cin.get(input, Limit, '#');
cout << "Here is your input:\n";
cout << input << "\nDone with phase 2\n";
cin.get(ch);
cout << "The next input character is " << ch << endl;//get()函数不会丢弃输入中的分界字符#
return 0;
}
输出:
Enter a string for getline() processing:
I am a handsome boy!
you know? #hhhh
Here is your input:
I am a handsome boy!
you know?
Done with phase 1
The next input character is h
Enter a string for get() processing:
I am a handsome boy!
you know? #hhhh
Here is your input:
I am a handsome boy!
you know?
Done with phase 2
The next input character is #