首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

cin.get 和cin.getline的有关问题

2012-03-23 
cin.get 和cin.getline的问题#includeiostreamusingnamespacestdintmain(){charstringOne[256]charstr

cin.get 和cin.getline的问题
#include   <iostream>  
using   namespace   std;  

int   main()  
{  
char   stringOne[256];  
char   stringTwo[256];  
char   stringThree[256];  

cout   < <   "Enter   string   one:   ";  
cin.getline(stringOne,256);  
cout   < <   "stringOne:   "   < <   stringOne   < <   endl;  

cout   < <   "Enter   string   two:   ";  
cin   > >   stringTwo;  
cout   < <   "stringTwo:   "   < <   stringTwo   < <   endl;  

cout   < <   "Enter   string   three:   ";  
cin.getline(stringThree,256);  
cout   < <   "stringThree:   "   < <   stringThree   < <   endl;  
return   0;  
}  
cin.get和cin.getline我看到的区别是前者将换行符放在缓冲区中,后者是抛弃换行符(我理解抛弃是既不在缓冲区也没保存)  
我的疑惑是第一个用cin.getline时stringtwo输出是换行了的,而在第二次用的时候stringthree却没有换行,不解啊,好像换cin.get也一样

[解决办法]
getline
Syntax:

#include <fstream>
istream& getline( char* buffer, streamsize num );
istream& getline( char* buffer, streamsize num, char delim );

The getline() function is used with input streams, and reads characters into buffer until either:

* num - 1 characters have been read,
* a newline is encountered,
* an EOF is encountered,
* or, optionally, until the character delim is read. The delim character is not put into buffer.

Those using a Microsoft compiler may find that getline() reads an extra character, and should consult the documentation on the Microsoft getline bug.
[解决办法]
http://blog.csdn.net/dyh1919/archive/2006/11/02/1363475.aspx
[解决办法]
原因是cin.getline 把回车吃进去了
cin没有
再次调用cin.getline 就会将没吃进去的回车 放到第三个里面去
你在第三个前加getchar();就正常了
[解决办法]
你都加了endl了,能不换行吗??????
getline与get会把串中的空格读入,而cin会在空格处停止读入,而且不读回车,会将换行符存入缓存。getline and get 都不会把换行符放入缓存的。
[解决办法]
cin.get(目标数组,长度,结束符号(默认 '\n ');
cin.getline(目标数组,长度,结束符号(默认 '\n ');

get遇到结束符或者超过长度减1的时候返回,保留结束符号在缓冲区。所以常常后面用cin.igone()手工忽略掉。
getline()同时从缓冲区读出结束符号,但是忽略掉,不用cin.igone()。

[解决办法]
修正一下,get是会把换行符放在缓冲区的,不信你试一试这样
#include <iostream>

int main()
{
using namespace std;

char arr[255];

cin.get(arr,254);
cout < < arr < < endl;
cin.getline(arr,254);
cout < < arr < < endl;
return 0;
}

热点排行