Reputation:
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;
}
Upvotes: 1
Views: 446
Reputation: 490018
If you'll forgive a probably-too-complete answer to a probable homework question:
while (cin >> y && y != '.')
capitals += (bool)isupper(y);
Upvotes: 0
Reputation: 32145
I think the error is operator precedence. !flag == -1
is equivalent to (!flag) == -1
. Try flag != -1
.
Upvotes: 0
Reputation: 2272
I think you need while (!(flag == -1))
... but it would be better to write while (flag != -1)
. The !
operator has higher precedence so it is evaluated before ==
.
Also you should try to use isupper()
to test for uppercase -- don't reinvent the wheel.
Upvotes: 0
Reputation: 992707
flag
is initialised to 0, !flag
is therefore 1, and your while loop is never entered.
You could fix this with:
while (!(flag == -1))
or
while (flag != -1)
Upvotes: 4
Reputation: 20262
Instead of !flag == -1
use flag != -1
.
!
is a unary logical NOT operator, and !0
is 1, not -1.
Upvotes: 2