cin.get()与cin.getline()的区别
2010-05-27 10:04
316 查看
cin.getline()和cin.get()都是对输入的面向行的读取,即一次读取整行(cin.get()可以读取一个单独字符)而不是单个数字或字符,但是二者有一定的区别。
cin.get()每次读取一整行并把由Enter键生成的换行符留在输入队列中,比如:
其输出为:
Please enter a sentence: You and I
Please enter another sentence: Sentence 1 is: You and I
Sentence 2 is:
请按任意键继续. . .
在这个例子中,cin.get()将输入的第一个句子读取到了chArr中,并将由Enter生成的换行符'/n'留在了输入队列(即输入缓冲区)中,因此下一次的cin.get()便在缓冲区中发现了'/n'并把它读取了,最后造成第二次的无法对地址的输入并读取。解决之道是在第一次调用完cin.get()以后再调用一次cin.get()把'/n'符给读取了,可以组合式地写为cin.get(chArr,1024).get();。
然而cin.getline()每次读取一整行并把由Enter键生成的换行符抛弃,如:
输出:
Please enter a sentence: You and I.
Please enter another sentence: He and she.
Sentence 1 is: You and I.
Sentence 2 is: He and she.
请按任意键继续. . .
由于由Enter生成的换行符被抛弃了,所以不会影响下一次cin.get()对地址的读取。
cin.get()每次读取一整行并把由Enter键生成的换行符留在输入队列中,比如:
char chArr[1024]; char chArr1[1024]; cout << "Please enter a sentence: "; cin.get(chArr, 1024); cout << "Please enter another sentence: "; cin.get(chArr1, 1024); cout << "Sentence 1 is: " << chArr << endl; cout << "Sentence 2 is: " << chArr1 << endl;
其输出为:
Please enter a sentence: You and I
Please enter another sentence: Sentence 1 is: You and I
Sentence 2 is:
请按任意键继续. . .
在这个例子中,cin.get()将输入的第一个句子读取到了chArr中,并将由Enter生成的换行符'/n'留在了输入队列(即输入缓冲区)中,因此下一次的cin.get()便在缓冲区中发现了'/n'并把它读取了,最后造成第二次的无法对地址的输入并读取。解决之道是在第一次调用完cin.get()以后再调用一次cin.get()把'/n'符给读取了,可以组合式地写为cin.get(chArr,1024).get();。
然而cin.getline()每次读取一整行并把由Enter键生成的换行符抛弃,如:
char chArr[1024]; char chArr1[1024]; cout << "Please enter a sentence: "; cin.getline(chArr, 1024); cout << "Please enter another sentence: "; cin.getline(chArr1, 1024); cout << "Sentence 1 is: " << chArr << endl; cout << "Sentence 2 is: " << chArr1 << endl;
输出:
Please enter a sentence: You and I.
Please enter another sentence: He and she.
Sentence 1 is: You and I.
Sentence 2 is: He and she.
请按任意键继续. . .
由于由Enter生成的换行符被抛弃了,所以不会影响下一次cin.get()对地址的读取。
相关文章推荐
- cin与cin.getline()的区别
- cin.get( )与cin.getline( )的区别
- cin.get( )与cin.getline( )的区别
- cin、cin.get()、cin.getline()、gets()区别与用法
- C++ cin.get()和cin.getline()方法详解及区别
- getline(),cin.getline(),cin.get()区别
- cin,cin.get,cin.getline的区别
- cin cin.get cin.getline有什么区别?(转载加部分原创)
- C++ 读书笔记之 getline与cin.getline的区别
- cin.get()与cin.getline()的区别
- cin.get()和cin.getline()之间的区别
- cin.get()和cin.getline()之间的区别
- cin.getline()、getline()、gets()、cin.get(),getchar()的区别
- cin.get( )与cin.getline( )的区别
- cin.get()和cin.getline()区别
- cin、cin.get()和cin.getline()的用法和区别
- cin.get getline cin.getline 区别以及‘n’是否留在缓冲区中
- C++中cin>> cin.get(char[], int) cin.getline(char[], int) cin.get(char)输入区别
- cin.get()与cin.getline()的区别
- cin.get()函数与cin.getline()函数的区别