int main (void)
{
char n;
label0:
cout<<"Please enter a character value(C/S)\n";
cin>>n;
n = toupper(n);
if ( n!= 'C' || n!= 'S' )
{
cout<<"Please enter proper value\n";
cin.clear();
cin.ignore();
goto label0;
}
else
{
cout<<"You entered"<<n<<"\n";
}
return 0;
}
In this code, even when I enter c C s S , it gives the same output as Please enter the proper value. Why is it not comparing?
if ( n!= 'C' || n!= 'S' )
This is true for every n in the world. You probably meant to use &&.
Think about it:
if n == 'C', then the condition is satisfied since n != 'S',
if n == 'S', then the condition is satisfied since n != 'C',
if n == 'X', then the condition is satisfied since n != 'C',
...
Read more about short circuit evaluation.
In general, you are having trouble by understanding the way in that logical operators are used.
The condition n != 'C' is equivalent to !(n == 'C').
Thus, the if() condition in your code can be rewritten in this way:
if ( !(n == 'C') || !(n == 'S') )
However, the condition you need in your code is another one:
if ( ! (n == 'C' || n == 'S') )
I suggest to do the job in reverse order:
if ( n== 'C' || n== 'S' )
{
cout<<"You entered"<<n<<"\n";
}
else
{
cout<<"Please enter proper value\n";
cin.clear();
cin.ignore();
goto label0;
}
In this way, if the entered character is c C s S, then the character is correct, and in any other case, a new character must be entered.
On the other hand, the goto statements must be used only in excepcional cases, when the flow of the program becomes very intrincated, and one really need "to jump out of the mess".
However, your program is very simple, and can be achieved with normal loop control sentences, such as do {} while():
int main (void)
{
char n;
do {
cout<<"Please enter a (proper) character value(C/S)\n";
cin>>n;
n = toupper(n);
cin.clear();
cin.ignore();
} while ( ! (n == 'C' || n == 'S') );
cout<<"You entered"<<n<<"\n";
return 0;
}
Now, the user is enforced to enter one of the desired characters: c C s S, until the entered character is correct.
Related
Why is this an infinite loop using || logical operator
char c;
std::cin >> c;
while( c != 'y' || c != 'Y' || c != 'N' || c != 'n')
but this is not
while( c != 'y' && c != 'Y' && c != 'N' && c != 'n')
I don't understand why && operator work here because logically thinking || operator is better fit.
Lets just look at the very smallest part:
c != 'Y' || c != 'N'
If c is 'Y' then it is not 'N', if it is 'N' then it is not 'Y'. Aka:
c | c != 'Y' || c != 'N'
Y | 1 || 0 = 1
N | 0 || 1 = 1
? | 1 || 1 = 1
If your logic always returns 1 no matter what, the loop will run forever. I assume you are looking to wait until you get c as one of these values, so write it logically.
I want to wait until c is one of ['y', 'Y', ...]
And you might be able to write some nicer code:
std::array<char> options = {{'y', 'Y', 'n', 'N'}};
while (std::none_of(std::begin(options), std::end(options),
[&c](char check) { return check == c; };)) {
std::cout << "Hey write the correct character!\n";
}
Untested!
You are checking the condition which is always true by using || operator,
( c != 'y' || c != 'Y' || c != 'N' || c != 'n')
This is always true ,because it would always satisfy at-least 3 conditions in your conditional statement .
if your char is n then it would satisfy remaining conditions
c!='y' , c!='Y' , c!='N' and similarly for any other character
I have an assignment where I have to make a program that allows a person to input a seven letter word and converts it to a telephone number (1-800-PAINTER to 1-800-724-6837 for example). I'm trying to make each letter convert to a specific number to be outputted to the user, with each letter corresponding to its number on a telephone keypad (so a, A, b, B or c, C equals 1, i.e, more info: https://en.wikipedia.org/wiki/Telephone_keypad).
Currently I have it set up so that each letter of the input word represents a char variable of one, two, three, four, five, six, or seven respectively. Then, using switch and if statements, the idea was to convert a char to an int variable of xtwo = 2, xthree = 3, etc. This isn't working however. Is there a better way to do this?
Example of code (up to first switch, though mostly it's a repeating pattern like so):
int main()
{
char one, two, three, four, five, six, seven;
cout << "Enter seven letter word (1-800-***-****): " << "\n";
cin >> one >> two >> three >> four >> five >> six >> seven;
int xtwo = 2; int xthree = 3; int xfour = 4; int xfive = 5; int xsix = 6; int xseven = 7; int xeight = 8;
int xnine = 9;
switch (one)
{
case 1:
if (one == 'a' || one == 'b' || one == 'c' || one == 'A' || one == 'B' || one == 'C')
{
one = xtwo;
}
break;
case 2:
if (one == 'd' || one == 'e' || one == 'f' || one == 'D' || one == 'E' || one == 'F')
{
one = xthree;
}
break;
case 3:
if (one == 'g' || one == 'h' || one == 'l' || one == 'G' || one == 'H' || one == 'L')
{
one = xfour;
}
break;
case 4:
if (one == 'j' || one == 'k' || one == 'l' || one == 'J' || one == 'K' || one == 'L')
{
one = xfive;
}
break;
case 5:
if (one == 'm' || one == 'n' || one == 'o' || one == 'M' || one == 'N' || one == 'O')
{
one = xsix;
}
break;
case 6:
if (one == 'p' || one == 'q' || one == 'r' || one == 's' || one == 'P' || one == 'Q' || one == 'R' || one == 'S')
{
one = xseven;
}
break;
case 7:
if (one == 't' || one == 'u' || one == 'v' || one == 'T' || one == 'U' || one == 'V')
{
one = xeight;
}
break;
case 8:
if (one == 'w' || one == 'x' || one == 'y' || one == 'z' || one == 'W' || one == 'X' || one == 'Y' || one == 'Z')
{
one = xnine;
}
break;
}
So, in essence, how can a char variable of a letter be converted to a specific int variable?
You could use a std::map.
For example, you could have
std::map<char,int> char_to_dig {
{'a',1}, {'b',1}, {'c',1},
{'d',2}, {'e',2}, {'f',2}
};
Then
char_to_dig['a']
will give you 1.
Alternatively, you could write a function that does the mapping. Something along the lines of this:
int char_to_dig(char c) {
static const char _c[] = "abcdefghi";
static const int _i[] = { 1,1,1,2,2,2,3,3,3 };
for (unsigned i=0; i<9; ++i) {
if (_c[i]==c) return _i[i];
}
return -1; // some value to signal error
}
Or, instead of using arrays, you could perform arithmetic on the chars (since they are just small integers).
int char_to_dig(char c) {
c = std::toupper(c);
if (c < 'A' || c > 'Z') return -1;
if (c == 'Z') return 9;
if (c > 'R') --c;
return ((c-'A')/3)+2;
}
This will give you numbers like on this pad:
Apparently, there's been a similar code golf question.
It has been years since I wrote any c/c++ code and I don't even have a compiler installed to test with .. but this should get you started on the right track
Check functions and syntax...all out of my head. Needs checking.
//
int numArray[7];
char inputStr[10];
cout << " give me 7 characters";
cin >> input;
/*
use a for loop to read the string letter by letter (a string in c is an
array of characters)
convert the characters to uppercase
fall through case statements for each group of letters
assing value to output array to do wiht as you like.
*/
for(i=0; i < 7; i++){
inputStr[i] = toupper(inputStr[i]);
switch(input[i]){
case 'A':
case 'B':
case 'C':
numArray[i] = 2;
break;
case 'D':
case 'E':
case 'F':
numArray[i] = 3;
break;
and so on and so foth....
}
}
i wrote this code about a program that should print males and females's average age but it doesn't work and I don't know why. Could anyone help me?
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int CountM,CountF,TotM,TotF,i,QP,Age;
float MediaM;
float MediaF;
char Sex[100];
CountM=0;
CountF=0;
TotF=0;
TotM=0;
QP=0;
cout<<"How many people do you want to analyze?"<<endl;
cin>>QP;
for(i=0;QP<i;i++)
{
cout<<"Enter Person sex "<<i+1<<endl;
cin>>Sex[i];
while((Sex[i] != 'M' || Sex[i] != 'm') && (Sex[i] != 'F' || Sex[i] != 'f')){
cout<<"The entered sex is invalid,enter M o F"<<endl;
cin>>Sex[i];}
cout<<"How many years?"<<endl;
cin>>Age;
if(Sex[i] == 'M' || Sex[i] == 'm'){
CountM++;
TotM=TotM+Age;}
else {
CountF++;
TotF=TotF+Age; }
}
MediaM=TotM/CountM;
MediaF=TotF/CountF;
cout<<"The average age of males is"<<MediaM<<endl;
cout<<"The average age of females is"<<MediaF<<endl;
return 0;
}
Thanks for help.
for (i = 0; QP < i; i++)
This line has a logic error; you want your for-loop to run QP Number of times. Hence, you should change the for-loop header to:
for (i = 0; i < QP; i++)
Another thing: your while loop condition logic is incorrect:
while((Sex[i] != 'M' || Sex[i] != 'm') && (Sex[i] != 'F' || Sex[i] != 'f'))
Here, if we see the Sex[i] != 'M' || Sex[i] != 'm', this will always be true, because even if Sex[i] is 'M', it cannot be 'm' at the same thie, hence you will have false OR true, which will lead to the while-loop condition being true, and not falsified, as you would want with the correct input being entered.
Hence change your for-loop condition to:
Sex[i] != 'M' && Sex[i] != 'm'
This error is replicated in other parts of your while loop condition. Fix that so that it works as expected.
I am trying to check if each character of a string in a string array is equal to any of the five vowels. However, when I test it to see when a vowel character in a string is equal to 'vowel', I get that they are not equal. The problem with the code is the bolded part below. Also, when I try to do "a" || "e" || "i" || "o" || "u", I get the error that ISO C++ forbids comparison between pointer and integer. How can I be able to check if they are equal? Thank you for your time.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <cmath>
#include <cstdlib>
using namespace std;
int l, c; //l is amount of letters in password, c is amount of letters being inputted
char letters[1000000]; //the letters being inputted
vector <string> pass; //string vector of the stored passwords
void rec(string current, int index, int x){ //determining all possible passwords
if (index >= 4){
pass.push_back(current);
}
else{
for (int i=0; i<c; i++){
if (x<i){
int old;
old = x;
x = i;
rec(current + letters[i], index+1, x);
x = old;
}
}
}
}
int main (int argc, char ** argv)
{
cin >> l >> c;
int x = -1;
for (int i=0; i<c ;i++){
cin >> letters[i];
}
sort(letters, letters + c); //sorted from least to greatest
rec("", 0, x);
for (int i=0; i<pass.size(); i++){
int vl=0; //number of vowels
int nvl=0; //number of non-vowels (consonants)
for (int j=0; j<l; j++){
**if (pass.at(0)[j] == 'a' || 'e' || 'i' || 'o' || 'u'){**
vl++;
}
else{
nvl++;
}
if (j == l-1){
if (vl >= 1 && nvl >= 2){
cout << pass.at(0) << endl;
}
}
}
}
return 0;
}
In C++, X || Y means:
Test if X is true. If so, result of whole expression is true
Otherwise, test if Y is true. Result of Y is result of expression.
So your code:
pass.at(0)[j] == 'a' || 'e'
(omitting for now the i etc. as they don't change anything).
We tested pass.at(0)[j] == 'a' . That was false, so now we test 'e'. Not that you did NOT test pass.at(0)[j] == 'e'. You just tested 'e'. This is the same as testing 'e' != 0, which is true. So your expression evaluates to true at this point (and does not go onto check 'i' etc.)
You probably intended to test whether pass.at(0)[j] held any of the values 'a', 'e', etc. If so then one way to encode that is:
if ( std::strchr("aeiou", pass.at(0)[j]) )
You should make sure j < strlen(pass.at(0)) before doing this though; using [] to generate an out of bounds index causes undefined behaviour.
Because you are using the || wrong. The part either side of || is a "true or false" expressin in itself, so you need something like:
if (pass.at(0)[j] == 'a' || pass.at(0)[j] == 'e' ... )
Otherwise, the expression is always true, since || is true if the expression on left or right is true, and 'e' is true by not being zero.
This does not do what you think...
(pass.at(0)[j] == 'a' || 'e' || 'i' || 'o' || 'u')
You need to explicitly compare,
char t = pass.at(0)[j];
if (t == 'a' || t == 'e' || t == 'i' || t == 'o' || t == 'u') {
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".