Reputation: 1
string str;
int i = 0, counter = 0;
cin >> str;
do
{
if(str[i] >= 'A' && str[i] <= 'Z')counter++;
cout << "Yes";
i++;
}while(str[i] != '\0');
A piece of code that takes a string from a user and outputs one single "Yes" if there are any capitals otherwise output nothing. This is from my test and I did not completely fulfill what was require in the instruction.
It works, but then when I type like "HHi" it will output "YesYes" when it should only be "Yes".
How can I ensure it only prints one "Yes" when it finds any amount of capitals?
Upvotes: 0
Views: 75
Reputation: 4458
This is an alternative answer to @Jonathan's answer. Simply you can achieve the same answer without using a break statement.
string str;
int i = 0, counter = 0;
cin >> str;
while(str[i] != '\0')
{
if(str[i] >= 'A' && str[i] <= 'Z')
counter++;
i++;
}
if(counter > 0)
cout << "Yes";
Upvotes: 1
Reputation: 946
You should output "Yes" inside your if statement and immediately break the while loop, e.g.:
string str;
int i = 0;
cin >> str;
while(str[i] != '\0')
{
if(str[i] >= 'A' && str[i] <= 'Z'){
cout << "Yes";
break;
}
i++;
}
(and it seems your code will break when the input is empty string.)
Upvotes: 0