输入流对象cin读取输入流的三种方式

来源:互联网 发布:python 私有属性 知乎 编辑:程序博客网 时间:2024/06/09 22:55

输入流对象cin读取输入流的三种方式

cin 输入流对象有三种读取控制台输入的方法。

分别为:

  • 使用“>>”运算符,这种方法只能读取单个单词,cin使用空白(空格、制表符和换行符)来确定字符串的结束位置
  • 使用getline()成员函数,getline()方法面向行的输入,它使用通过回车键输入的换行符来确定输入结尾,但是getline()方法并不保存换行符,在存储字符串时,它用空字符来替换换行符
  • 使用get()成员函数,get()方法也是面向行的输入,它和getline()接受的参数相同,解释参数的方式也相同,并且都读取到行尾。但是get()不再读取并丢弃换行符,而是将其保留在输入队列中

以下是程序实例

1、利用">>"运算符来读取字符串:

//instr1.cpp -- reading more than one string#include <iostream>int main(){    using namespace std;    const int Arsize = 20;    char name[Arsize];    char dessert[Arsize];    cout << "Enter your name:\n";    cin >> name;    cout << "Enter your favorite dessert:\n";    cin >> dessert;    cout << "I have some delicious " << dessert;    cout << " for you, " << name << ".\n";    return 0;}

程序运行情况为:

Enter your name:River HeEnter your favorite dessert:I have some delicious He for you, River.

2、利用成员函数getline()来读取字符串:

//instr2.cp -- 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 favourite desset:\n";    cin.getline(dessert, Arsize);    cout << "I have some delicious " << dessert;    cout << " for you, " << name << ".\n";    return 0;}

程序运行情况为:

Enter your name:River HeEnter your favorite dessert:Chocolate MouseI have soem delicious Chocolater Mouse for you, River He.

3、利用成员函数get()来读取字符串:

//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 favourite dessert:\n";    cin.get(dessert, Arsize).get();    cout << "I have soem delicious " << dessert;    cout << " for you, " << name << ".\n";    return 0;}

程序运行情况为:

Enter your name:River HeEnter your favorite dessert:Chocolate MouseI have soem delicious Chocolater Mouse for you, River He.

以上实例来源于“C++ Primer Plus”,三个例子分别呈现了三种方法的特点,实例1,是由于“>>”遇到空格符后就结束读取,分别将River和He存取到了name和dessert变量中,而实例2中,getline()方法是根据换行符确定读取结束的,所以输出符合预期。而实例3中,由于前一行输入滞留了换行符,会导致第二次读取时直接结束,因此采用了这样一种方式:

cin.get(name, ArSize).get()
第一个get()读取了输入字符串到name,第二个读取了换行符,相当于清空了输入队列,为下次读取做准备。因此,我们可以使用这样一种方式去读取字符串。

所以在实际使用过程中,要根据输入流的特点正确选择输入流,而getline()get()的区别在于,get()是输入更加仔细,如何知道停止读取的原因是由于已经读取了整行,而不是由于数组已经填满呢?查看下一个输入字符,如果是换行符,说明读取了整行;否则,说明该行中还有其他输入。

0 0