getche()with while循环

时间:2015-11-12 21:31:57

标签: c++ loops while-loop

我想创建一个简单的程序来计算其中的单词和字符数。

我找到了以下代码示例:

char ch = 'a';
int Wcont = 1; // to count the number of words in the phrase
int Chcont = 0;
while (ch != '\r'){
ch = getche();
if ( ch == ' ' ) 
   Wcont++
// to the end of program 
}
  

输入:欢迎

     

输出:Wcont = 1,Chcont = 8

如果改变条件:

if ( ch == ' ' || ch == '\r')

然后单词数增加1 和字符数减少1

  

输入:Welocme

     

输出:Wcont = 2,Chcont = 7

我不明白getche()如何运作以及它如何与屏幕互动。我也想知道为什么条件有ch == '\r'以及当ch == '\r'为假时循环必须停止的原因。

1 个答案:

答案 0 :(得分:0)

while循环测试上一次char读取,然后读取下一个读取。您应该使用以下内容:

while ((ch = getche()) !='\r')

或者:

    while(true)
    {
     ch = getche();
     if(ch=='\r')
      break;
.....
    }