1.用get函数读入一个字符
(1)无参数的get函数
cin.get() //从指定输入流中提取一个字符
(2)由1个参数的get函数
cin.get(c) //从指定输入流中读取一个字符,赋值给字符变量c
(3)由3个参数的get函数
cin.get(/*字符数组*/str,/*字符个数*/n,/*终止字符*/'/') //从指定输入流中读取n-1个字符,赋给str,若在读取n-1个字符前遇到指定的终止字符,则提前结束读取
2.用getline函数读入一行字符
cin.getline(/*字符数组*/str,/*字符个数*/n,/*终止字符*/'/') //从输入流中读取一行字符,用法与带3个参数的get函数类似,但有细微差异
3.getline函数与get函数的区别
使用get函数提取输入流中的字符时,遇到终止字符,可以理解为读取指针停在终止字符前,且终止字符仍保留在输入序列,第二次调用get函数,如果终止字符没变,那么相当于第二个get函数直接遇到终止字符,直接进入下一行程序;如果第二个get函数的终止字符更改,那么输出的第二个get函数返回值将先输出第一个终止字符。
如下:
前后两个get函数终止字符相同
#include<iostream>
using namespace std;
int main()
{
int ch;
char a[20];
cout << "Please enter a sentence:";
cin.get(a, 20, '/');
cout << "The first sentence is:" << a << endl;
ch = cin.peek();
cout << "The next character(ASCII code) is:" << ch << endl; //观察到的字符是“/”的ASCII码,而不是空格字符的ASCII码
cout << "Please enter next sentence:";
cin.get(a, 20, '/'); //直接跳过了第二个get函数
cout << " The second sentence is:" << a << endl;
return 0;
}
前后两个get函数终止字符不同
#include<iostream>
using namespace std;
int main()
{
int ch;
char a[20];
cout << "Please enter a sentence:";
cin.get(a, 20, '/');
cout << "The first sentence is:" << a << endl;
ch = cin.peek();
cout << "The next character(ASCII code) is:" << ch << endl; //观察到的字符是“/”的ASCII码,而不是空格字符的ASCII码
cout << "Please enter next sentence:";
cin.get(a, 20, '\\'); //输出将包含第一个get函数的终止字符
cout << " The second sentence is:" << a << endl;
return 0;
}
getline函数读取输入流中的字符,遇到终止字符后将丢弃终止字符,因此终止字符不会留在输入序列,第二次调用getline函数是不会跳过,程序如下:
#include<iostream>
using namespace std;
int main()
{
int ch;
char a[20];
cout << "Please enter a sentence:";
cin.getline(a, 20, '/');
cout << "The first sentence is:" << a << endl;
ch = cin.peek(); //观察到的是‘I’的ASCII码
cout << "The next character(ASCII code) is:" << ch << endl;
cout << "Please enter next sentence:";
cin.getline(a, 20, '/');
cout << " The second sentence is:" << a << endl;
return 0;
}