输入流对象cin读取输入流的三种方式
2016-04-18 16:04
543 查看
输入流对象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 He Enter 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 He Enter your favorite dessert: Chocolate Mouse I 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 He Enter your favorite dessert: Chocolate Mouse I 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()是输入更加仔细,如何知道停止读取的原因是由于已经读取了整行,而不是由于数组已经填满呢?查看下一个输入字符,如果是换行符,说明读取了整行;否则,说明该行中还有其他输入。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性