注册 登录
编程论坛 C++教室

C++primer中关于getline使用循环的问题

w470913537k 发布于 2013-03-19 18:31, 2690 次点击
程序主干如下:
int main ()
{
    string line;
    while (getline(cin,line))
           cout<<line<<endl;
    return 0;
}
11 回复
#2
w470913537k2013-03-19 18:32
我想说的是,这个程序无法终止循环,在iostream输入流中,书上解释说如果遇到不符合的输入流则将终止从流中读取数据,可是这样输入字符串怎么才能终止?书中这个小程序是不是有点问题,该改改。我直接打回车是没法终止的,对于getline函数,如果首字符是回车,那么字符串为空。
#3
peach54602013-03-19 18:50
好像是ctl+z吧...
#4
gwcome2013-03-19 18:58
At end of file.
After the function extracts an element that compares equal to delim, in which case the element is neither put back nor appended to the controlled sequence.
After the function extracts is.max_size() elements, in which case the function calls setstate(ios_base::failbit).
#5
gwcome2013-03-19 19:01
msdn上搬过来的
#6
luoshibin1382013-03-19 22:07
打回车怎么就能终止呢?回车是正常的输入,不算“不符合的输入流”,想退出就自己写个退出条件憋。“不符合的输入流”估计用户在键盘输入时也很难输入,如果可以很容易输入,那程序不是经常会终止,所以还是自己写个退出条件吧!如:
   int main(int argc,char*argv[])
  4 {
  5     string line;
  6     while (getline(cin,line)){
  7         cout<<line<<endl;
  8         if(line=="q") break;
  9     }
 10     return 0;
}
#7
w470913537k2013-03-19 22:23
回复 6楼 luoshibin138
嗯嗯。。。我也觉得是这样。。看来是书上有点问题。
#8
gwcome2013-03-20 10:19
回复 6楼 luoshibin138
为什么我的编译器变异通不过
程序代码:
#include <iostream>
using namespace std;
int main(int argc,char*argv[])
{
         string line;
         while (cin.getline(cin,line)){
             cout<<line<<endl;
            if(line=="q") break;
               
         }
return 0;
}

1、error C2664: “std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::getline(_Elem *,std::streamsize)”: 不能将参数 1 从“std::istream”转换为“char *”
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]
1>        没有可用于执行该转换的用户定义的转换运算符,或者无法调用该运算符
2、fatal error C1903: 无法从以前的错误中恢复;正在停止编译
#9
qq3725058552013-03-20 12:34
字符串的结束好像是'\0'
#10
luoshibin1382013-03-20 22:15
你的代码多了一个cin是什么意思:我改了下不知是你想要的不

  #include<iostream>
  2 using namespace std;
  3 main(int argc,char*argv[]){
  4     string line;
  5     while (getline(cin,line)){
  6         cout<<line<<endl;
  7         if(line=="q") break;
  8     }
  9 }
#11
jimi19932013-03-21 20:25
这个getline的异常输入貌似是EOF(End of file)吧。。然后windows下是ctrl+z,..貌似linux是ctrl+d…………
#12
heroinearth2013-10-03 15:15
连按两次Ctrl+z,
1