C ++使用while循环 [英] C++ Using a while loop

查看:259
本文介绍了C ++使用while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个c ++程序来读取一行输入的代码(例如The Hat是平的),并让程序输出该代码所具有的大写字母数。 (在这个例子中,它必须输出2)。我已经写了一段代码使用 cin.get()但我的代码没有进入while循环。请帮帮我。并请仅更改我的代码。

I'm trying to write a c++ program to read a line of inputed code (eg The Hat is flat) and get the program to output the number of capital letters the code has. (in this example it would have to output 2). I have written a piece of code using cin.get() but my code is not entering the while loop. Please help me. and please change 'my code' only.

#include <iostream> 
using namespace std; 

int main () 
{
    char y = 0; 
    int capitals = 0; 
    int flag = 0;

    cout << "Enter your line of words followed by a fullstop: "; 

    while (!flag == -1)
    {
        cin.get(y);
        if ((y >= 65) && (y <= 90))
        {
             capitals = capitals + 1; 
        }         

        if (y == 46)
        {        
            flag = -1; 
        }
    }

    cout << "Number of capitals equal is this line is: " << capitals << endl;
    return 0; 
}


推荐答案

标志初始化为0,因此!flag 为1,并且从不输入您的while循环。

flag is initialised to 0, !flag is therefore 1, and your while loop is never entered.

您可以用以下方法解决这个问题:

You could fix this with:

while (!(flag == -1))

while (flag != -1)

这篇关于C ++使用while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆