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

为什么我的程序不会跳出while循环??

wtyj112 发布于 2009-10-26 15:14, 4455 次点击
#include <iostream>
#include <string>
using namespace std;


int main()
{
    string word;
   
    while ( cin >> word )
          cout << "word read is: " << word << '\n';
         
    cout << "ok: no more words to read: bye!\n";
    return 0;
}

输入my first c++ program 回车以后怎么不结束while循环?
我用dev-c++来调试的.
11 回复
#2
qlc002009-10-26 16:04
你没有设置结束标志,所以不会退出!
加一个if条件语句
#3
gah1682009-10-26 16:06
应该是while语句后面没有大括号吧,要养成良好的编程习惯啊不知对不对,嘿嘿,我还是个新手~~~不对请楼下指出~
#4
qlc002009-10-26 16:11
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string word;
     
    while ( cin >> word )
    {
         
        if(word=="0")
        break;
        cout << "word read is: " << word << '\n';
    }
    cout << "ok: no more words to read: bye!\n";
    return 0;
}
在while语句里面加if语句就可以了!
#5
wtyj1122009-10-26 19:15
我的理解是cin输入 当回车的时候应该 cin >> word 这个语句判断为错.
#6
wtyj1122009-10-26 19:16
我说错了应该是判断为 非 然后while应该结束
#7
cookies50002009-10-26 22:03
cin >> word  是让你输入一个字符串,"word" 已被你声明为string了。

qlc00正解。
#8
gz812009-10-26 22:54
以下是引用wtyj112在2009-10-26 15:14:05的发言:

#include <iostream>
#include <string>
using namespace std;


int main()
{
    string word;
   
    while ( cin >> word )
          cout << "word read is: " << word << '\n';
         
    cout << "ok ...
想跳出循环,按住ctrl键不放再按z键,屏幕上出现^Z,再按回车即可。

ctrl+z表示“文件结束符”,cin读到文件结束符会会变为false,所以跳出循环。
#9
AngzAngy2009-10-27 13:49
#include <iostream>
#include <string>
using namespace std;
 
 
int main()
{
    string word;
     
    while ( (cin >> word )&&(word!="#"))
          cout << "word read is: " << word << '\n';
           
    cout << "ok: no more words to read: bye!\n";
    return 0;
}
 //输入结束时,再输入一个#好就完了
#10
newCpp2009-10-27 23:12
程序代码:
#include <iostream>
#include <string>
using namespace std;
 
 
int main()
{
    string word;
     
    while (cin>>word&&word!="0")
          cout << "word read is: " << word << '\n';
           
    cout << "ok: no more words to read: bye!\n";
    return 0;
}
这样输入0就结束了!
呵呵
#11
quietstar2009-11-10 22:41
感觉while不是这么写的,附上我写的程序,vc++6.0编译通过:


#include <iostream>
#include <string>

using namespace std;

int main()
{
    string word;
    while(word != "0")
    {
        cout<<"Please input your word:";
        cin>>word;
        cout<<"word read is:"<<word<<endl;        
    }
    cout<<"ok: no more words to read: bye!\n";
    return 0;
}
#12
今生唯一2010-11-11 01:31
ctrl+z 不行啊
我按照楼上的说的做的,可是必须输入2次 ctrl+z 才可以结束循环,为什么啊???
   对了,我用的是c++6.0版本。
1