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

请教一下如何结束while(cin>>str)

fl8962 发布于 2014-02-25 05:12, 598 次点击
比如:
int main()
{
 int i=0;
string str;
while(cin>>str)
 {
    i++;
  }
 if(i>0)
  {
    cin>>i;
  }
  cout<<i<<endl;
  return 0;
}
请问如何结束这个输入字符串的while循环而执行下面的语句呢?我在网上查有人说 ctrl+z,ctrl+d。 我都试了,这两个会直接跳出程序而不是跳出循环。
5 回复
#2
tj060511022014-02-25 09:17
break;
#3
zklhp2014-02-25 09:23
程序代码:

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main(void)
{
    int i=0;
    string str;
    while(cin>>str)
    {
        i++;
    }
    if(i>0)
    {
        cin>>i;
        cout << "执行过这里" << endl;
    }
    cout<<i<<endl;
    return 0;
}


我的C++也是新学的 共同学习

这里加了一条输出 发现其实是有输出的 说明你输入的文件结束符跑到了这里 C语言里面的输入输出也有这个问题。。
#4
i802862014-02-25 10:29
int main()
{
int i=0;
string str;
while(cin>>str)
{
    i++;
}
cin.clear();/*标志位复位*/
cin.sync();/*清空缓冲区*/
if(i>0)
{
    cin>>i;
}
cout<<i<<endl;
return 0;
}
#5
fl89622014-02-26 01:26
回复 3楼 zklhp
en , wo jiu shi yi zhi gao bu qing chu ru he jie shu zhe yang de xun huan, lou xia de jie jue fang shi shi dui de ...
// yeah, I do not know how to kill this kind of while loop, and the next floor gave right way to solve this problem, and maybe you can learn something from him too.
#6
fl89622014-02-26 01:26
回复 4楼 i80286
Thanks.
1