首页 新闻 会员 周边

C++中I/O的 get 和 getline 问题。

2
悬赏园豆:20 [已关闭问题] 关闭于 2010-12-23 17:46
代码
1 #include <iostream>
2 const int SLEN = 10;
3 inline void eatline(){while (std::cin.get() != '\n') continue;}
4 int main()
5 {
6 using namespace std;
7 char name[SLEN];
8 char title[SLEN];
9 cout << "Enter your name:\n";
10 //cin.getline(name, SLEN);//这个会有问题
11 cin.get(name, SLEN);//OK
12 if(cin.peek() != '\n')
13 {
14 cout << "Sorry,we only have enough room for "
15 << name << endl;
16 }
17 eatline();
18 cout << "Enter your title:\n";
19 cin.get(title, SLEN);
20 if (cin.peek() != '\n')
21 {
22 cout << "We were forced to truncate your title.\n";
23 }
24 eatline();
25 cout << " Name: " << name
26 << "Title: " << title << endl;
27 }

注释处,当使用getline的时候,输入的name大于10个字符时,程序无法看到后面的cout输出部分。

而使用get的时候正常。书上说,当输入字符大于SLEN-1的时候,下一字符如果不是换行符,getline

会触发failbit位置位,导致输入终止。我的理解是可能会是eatline中的死循环。但一直想不通,因为输

入队列中应该会有'\n'。当输入字符超过设定数目的时候,getline 是不会对后续的字符(包括换行符)

采取预读丢弃处理的。

Vman的主页 Vman | 初学一级 | 园豆:184
提问于:2010-12-18 19:07
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册