C++ Using a while loop - c++

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;
}

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)

Instead of !flag == -1 use flag != -1.
! is a unary logical NOT operator, and !0 is 1, not -1.

Have you tried this?
while (!(flag == -1))
or
while (flag != -1)

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.

I think the error is operator precedence. !flag == -1 is equivalent to (!flag) == -1. Try flag != -1.

If you'll forgive a probably-too-complete answer to a probable homework question:
while (cin >> y && y != '.')
capitals += (bool)isupper(y);

Related

unexpected infinite loop in c++

I'm working in a project and the task is to make the signup function
so when I try several test cases in password function I got stuck in an infinite loop when I try to type an invalid password without giving me a chance to retype the password.
Thanks in advance...
#include <iostream>
#include <string>
#include <cstring>
#include <conio.h>
#include <stdio.h>
using namespace std;
#define size 40
int main(){
bool flag = true;
while (flag){
bool flagS = false, flagN = false; int count = 0;
char password[size] = { 0 };
cout << "Type your Password .....\n Note :: Must be more than 8 characters including at least one number and one special character...\n";
cin.get(password, size);
count = strlen(password);
for (int z = 0; z < count; z++){
if (password[z] >= 48 && password[z] <= 57)
flagN = 1;
if ((password[z] >= 33 && password[z] <= 47) || (password[z] >= 58 && password[z] <= 64))
flagS = 1;
}
if ((flagS == 1) && (flagN == 1) && (count >= 8))
{
cout << "Valide Password ...\nCongrats!! ..you created a NEW account.." << endl;
flag = false;
}
else
{
cout << "invalide password..\nPlease try again..\n";
flag = true;
}
}
}
You must write cin inside of while loop. And this will fix your problem:
#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
#define size 40
int main(){
bool flag = true;
bool flagS = false, flagN = false; int count = 0;
char password[size] = { 0 };
cout << "Type your Password .....\n Note :: Must be more than 8 characters including at least one number and one special character...\n";
while (cin >> password && flag){
count = strlen(password);
for (int z = 0; z < count; z++){
if (password[z] >= 48 && password[z] <= 57)
flagN = true;
if ((password[z] >= 33 && password[z] <= 47) || (password[z] >= 58 && password[z] <= 64))
flagS = true;
}
if ((flagS) && (flagN) && (count >= 8))
{
cout << "Valide Password ...\nCongrats!! ..you created a NEW account.." << endl;
flag = false;
}
else
{
cout << "invalide password..\nPlease try again..\n" << "Type your Password .....\n Note :: Must be more than 8 characters including at least one number and one special character...\n";;
flag = true;
}
}
}
std::istream::get does not remove the newline from the stream. This means the next call to std::istream::get immediately finds the newline and reads nothing into the buffer, sets the failbit, and returns. Because the steream is now in the fail state all subsequent reads instantly fail. You could cin.ignore() the newline, but a more direct approach is to use std::istream::getline because it removes the newline for you.
Always test the stream state after an IO transaction to make sure it succeeded.
Side note:
Prefer to use std::string and std::getline to raw character arrays and functions that use them. std::istream::get and std::istream::getline both mark the stream as failed if the buffer provided is too small. The string provided to std::getline will be resized, so as long as you have dynamic storage remaining, buffer over runs and the errors raised to prevent them are a non-problem. If the system cannot allocate a buffer of sufficient size for the string an exception is thrown to make you aware of the problem.
Prefer to use letters, for example 'A' to a raw ASCII code. For one thing the intent of 'A" is immediately recognizable to even the most raw of programmers and there is always the possibility that the implementation does not use ASCII as the default encoding.

Keeping Tally of Characters in Arrays

I'm working on a Caesar Cipher program for an assignment and I have the general understanding planned out, but my function for determining the decipher key is unnecessarily long and messy.
while(inFile().peek != EOF){
inFile.get(character);
if (character = 'a'|| 'A')
{ aCount++; }
else if (character = 'b' || 'B')
{ bCount++; }
so on and so on.
What way, if it's possible, can I turn this into an array?
You can use the following code:
int count [26] = {0};
while(inFile().peek != EOF){
inFile.get(character);
if (int (character) >=65 || int (character) <=90)
{ count [(int (character)) - 65] ++; }
else if (int (character) >=97 || int (character) <=122)
{ count [(int (character)) - 97] ++; }
}
P.S. This is checking for the ASCII value of each character and then increment its respective element in the array of all characters, having 0 index for A/a and 1 for B/b and so on.
Hope this helps...
P.S. - There was an error in your code, = is an assignment operator and == is a conditional operator and you do not assign value in if statement, you check for condition... So always use == to check for equality...
You can use an array in the following manner
int letterCount['z'] = {0}; //z is the highest letter in the uppercase/lowercase alphabet
while(inFile().peek != EOF){
inFile.get(character);
if (character > 'A' && character < 'z')
letterCount[character]++;
}
You can also use a hashmap like this
#include <unordered_map>
std::unordered_map<char,int> charMap;
while(inFile().peek != EOF){
inFile.get(character);
if (charMap.find(character) == charMap.end())
charMap[character] = 1;
else
charMap[character] = charMap[character] + 1;
}
In case you do not know, a hashmap functions as an array, where the index can be any class you like, as long as it implements a hash function.

how to check char array with nested if statement?

As you might be able to tell im trying to introduce a counter for how many consonants there are in a certain string, but the output is always 50, unless spaces are involved.
int main(){
char input[50];
int total = 0;
cout << "Enter a string of no more than 50 characters\n";
cin.getline(input,50);
for(int n = 0; n<50;n++){
if(input[n]!='a',input[n]!='A',input[n]!='e',input[n]!='E',input[n]!='i',input[n]!='I',input[n]!='o',input[n]!='O',input[n]!='u',input[n]!='U',input[n]!=' ')
total++;}
cout << total << endl;}
According to wikipedia, comma operator is defined as follows
In the C and C++ programming languages, the comma operator
(represented by the token ,) is a binary operator that evaluates its
first operand and discards the result, and then evaluates the second
operand and returns this value (and type).
In your case, you should use logical AND (&&) instead of comma operation.
More efficiently, you may rewrite your code like this
char c = tolower(input[n]);
if (c >= 'a' && c <= 'z' && c != 'a' && c != 'e' && c != 'i' && c != 'o' && c !='u')
total++;
It will include all the cases.
As everyone has clearly explained, you need to use && operator to ensure all conditions are checked.
if(input[n]!='a' && input[n]!='A' && input[n]!='e' && input[n]!='E' && input[n]!='i' && input[n]!='I' && input[n]!='o' && input[n]!='O' && input[n]!='u' && input[n]!='U' && input[n]!=' '){
total++;
}
One recommendation to avoid multiple checks:
Extract the character to a variable converted to lower or upper case.
char c = input[n] | 32;
Regarding the ',' used; this program might provide more insight along with the WIKI shared :
void main(){
int a=-1;
if(++a,a, a++){ // Works like "||"
printf("Yes %d",a);
}else {
printf("NO %d", a);
}
}
Output: NO 1

continue program in c++

my program is
#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int exit;
while(1==1)
{
float a,b,c;
printf("Enter length(in metre)");
scanf("%f",&a);
printf("Enter width(in metre)");
scanf("%f",&b);
printf("Enter height(in metre)");
scanf("%f",&c);
if(5.919<a<=12.056 && 2.340<b<=2.347 && 2.380<c<=2.648)
{
printf("40' high cube \n");
}
else if(a<=5.662 && 2.340<b<=2.438 && c<=2.16)
{
printf("20' open top");
}
else
{
printf("40' flat rack");
}
cout << "Would you like to exit?(Yes/No)"<<endl;
cin >> exit;
if(exit == 1)
{
break;
}
}
return 0;
}
But, the code is given wrong asnwers.No matter whatever feed i give..it is selecting 40" high cube
Also,I want to input yes/no to continue,instead of 1. How should I do it?
Unfortunately, while the following is valid syntactically, it does not do what you expect:
5.919<a<=12.056
This is parsed as (5.919 < a) <= 12.056 and works as follows: a is compared to 5.919, and the result of that comparison (0 or 1) is compared to 12.056. Since both 0 and 1 are less than 12.056, the overall expression always evaluates to 1.
To fix, rewrite it as:
5.919 < a && a <= 12.056
The same goes for all the other similar expressions.
For input yes/no, You can use this way..
char exit;
// in while loop waiting for user input
exit = getch();
if(exit == 'y' || exit == 'Y' )
break;
//else again go for input.
This line isn't doing what you think.
if(5.919<a<=12.056 && 2.340<b<=2.347 && 2.380<c<=2.648)
to do what you seem to want, you would need to change it to:
if(5.919<a&& a<=12.056 && 2.340<b&& b<=2.347 && 2.380<c&& c<=2.648)
same for this line:
else if(a<=5.662 && 2.340<b<=2.438 && c<=2.16)
that needs to be changed to:
else if(a<=5.662 && 2.340<b && b <=2.438 && c<=2.16)
When you write this:
2.340 <b <= 2.347
what C and C++ understand is (2.30 < b) <= 2.347 and that is always true (1 in C) for all values of b because (2.30 < b) is either 0 or 1, which is always less or equal than 2.347. This is arcane and backwards, but it is how C and C++ see the world. I'm sure that this will only bite you once, and this was your turn.
Also, it is bad practice to mix printf and scanf with cin and cout, make a choice about how you want to do your I/O and stick to it, mixing them brings other subtle bugs that are difficult to troubleshoot.
For the final part of your question, you can do:
#include<stdio.h>
#include<string.h>
int main(void){
char answer[16];
printf("Yes or No\n");
scanf("%s",answer);
if (strncmp(answer,"Yes",3)==0){
printf("yes\n");
}else{
printf("no\n");
}
}
For the second part question :
Change the condition to Y/N instead of 1 and 0. Use character data type, or string or anything similar. And then you can compare the input with "exit".

My program run and returns 0, but it doesn't display the cout data ive given it

When I Build and run my code it instantly returns 0 saying programing was successful, however i want it to display all the numbers from 100 to 200 that are divisible by 4.
Here's my code...
#include <iostream>
using namespace std;
int main()
{
int num = 200;
int snum;
cout<<"The following numbers are all divisble by 4 and are inbetween 100 and 200\n";
while(num<99)
{
snum = (num % 4) ;
cout<<snum<<endl;
cout<<num<<endl;
if(snum = 0)
{
cout<< num << endl;
}
else
{
}
num--;
}
return 0;
}
The while condition should be while (num > 99) instead of while(num<99)(false at the beginning)
The if condition should be if (snum == 0) instead of if(snum = 0)(= is assignment, not equal operator)
The else part has nothing, you may delete it. I added some other notes in the comments below.
while (num > 99)
{
snum = num % 4 ; // no need for the parenthesizes
if (snum == 0)
{
std::cout<< num << std::endl;
}
--num; //pre-increment is preferred, although doesn't matter in this case
}
Your loop never executes because the condition
(num<99)
is already false from the start. You probably meant
(num>99)
Also, the if statement condition
(snum = 0)
sets snum to zero, always returning zero, so you probably meant
(snum == 0)
You set num to be 200:
int num = 200;
Then you only run the loop if and when the number is less than 99:
while(num<99)
What do you expect will happen?
This is not how you do an equals-test in C:
if(snum = 0)
In C, equality is checked with ==:
if(snum == 0)
In fact, what you have (if (snum = 0)) will NEVER be true, so your if-statement will NEVER be executed.