Error Message:
What does this mean?
And how do I fix it?
error C2040: '==' : 'int' differs in levels of indirection from 'const char [2]'
Code:
#include <iostream>
#include <cmath>
using namespace std;
int round(double number);
//Assumes number >=0.
//Returns number rounded to the nearest integer.
int main()
{
double doubleValue;
char ans;
do
{
cout << "Enter a double value: ";
cin >> doubleValue;
cout << "Rounded that number is " <<round(doubleValue)<< endl;
cout << "Again? (y/n): ";
cin >> ans;
}
//Here is the line generating the problem, while(...);
while (ans == 'y' || ans == "Y");
cout << "End of testing.\n";
return 0;
}
//Uses cmath
int round(double number)
{
return static_cast<int>(floor(number + 0.5));
}
You need to single-quote char literals. You did this correctly for the first one but not the second:
while (ans == 'y' || ans == "Y");
This should be:
while (ans == 'y' || ans == 'Y');
Double quotes are for string (const char[]) literals.
You have double quotes instead of single ones on this line:
while (ans == 'y' || ans == "Y");
The capital Y is contained in double quotes, which creates a const char [2] (Y followed by null). You probably ment:
while (ans == 'y' || ans == 'Y');
I dont know this is useful or not but it may be like following:
while ((ans == 'y') || (ans == 'Y'));
Related
I am not sure what I'm doing wrong here, every time I run it, it goes through the if part even when it's not true? So the 'else' never runs.
#include <iostream>
using namespace std;
string choice;
float numb;
float convert(float numb,string choice)
{
float newNo;
if (choice == "F" or "f"){
newNo = numb * 0.2 * 9 + 32;
}else{
newNo = (numb - 32) / 1.8;
}
return newNo;
}
int main()
{
cout << "welcome to Temperature converter v0.1" << endl;
cout << endl;
cout << "Which conversion would you like to use?" << endl;
cout << "type C to convert to Celsius and F to convert to Fahrenheit - ";
cin >> choice;
cout << "what number would you like to convert? - ";
cin >> numb;
cout << convert(numb,choice);
return 0;
}
The problem is your if Statement:
if (choice == "F" or "f"){
basically, what you say here is:
If choise is "F" or if "f". You need to understand: True is everything besides zero (0). "f" is NOT zero, so it is true. You could also wirte (or = ||):
if (coice == "F" || true)
which is the same like:
if (true)
So in order for your code to work, you need:
if (choice == "f" || choice == "F")
That would do what you expect.
There is a problem in the syntax of 'if' statement. Following is the corrected code, where '||' stands for 'or':
if ((choice == "F") || (choice=="f")){
newNo = numb * 0.2 * 9 + 32;
}else{
newNo = (numb - 32) / 1.8;
}
Change this if statement
if (choice == "F" or "f"){
to the following
if (choice == "F" or choice == "f"){
Otherwise the right operand of the operator or
"f"
is always equal to true because it is converted to the address of the first character of the string literal that evidently is not equal to 0.
That is your original condition in the if statement looks like
if (choice == "F" or "f" != nullptr){
and indeed "f" != nullptr
I am working on a project right now and when I try to run what I have below it gives me an error that says "uninitialized local variable 'userOption' used" on line 22, while (isValidOption(userOption) == true) {.
How do I fix that error? Thank you.
#include<iostream>
#include <string>
using namespace std;
char toupper(char ch) {
if (ch >= 'A'&&ch <= 'Z')
return(ch);
else
return(ch - 32);
}
bool isValidOption(char ch) {
if (ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X')
return(true);
else
return(false);
}
char getMainOption() {
string UserInput;
char userOption;
while (isValidOption(userOption) == true) {
cout << "Choose One of the following options\n";
cout << "I--List Our Inventory\n";
cout << "O--Make an Order\n";
cout << "L--List all Orders made\n";
cout << "X--Exit\n";
cout << "Enter an option: ";
getline(cin, UserInput);
userOption = toupper(UserInput[0]);
if (!isValidOption(userOption)) {
cout << "Invalid String\n";
cout << "Enter an option: ";
getline(cin, UserInput);
userOption = toupper(UserInput[0]);
}
if (userOption == 'I')
cout << "Listing Our Inventory\n";
else if (userOption == 'O')
cout << "Make an order\n";
else if (userOption == 'L')
cout << "Listing all orders\n";
}
return userOption;
}
int main() {
char choice;
choice = getMainOption();
system("pause");
return 0;
}
What the error is saying that you're trying to read from userOption before you've ever written to it. If a variable is uninitialized, its memory contents will be full of junk left behind by other functions and it can easily cause bugs. In your case, you'll want to read input from the user into userOption before you do any logic on it. This can be done with a do-while loop:
char userOption; // not yet initialized
do {
...
cin >> userOption; // userOption gets initialized here on first loop run
} while (isValidOption(userOption)); // no need for == true, that's a tautology :-)
// NOTE: perhaps you want to loop while the input is INvalid, as in
// while (!isValidOption(userOption)); ?
A couply code-review comments I would additionally give are:
std::toupper already exists in <cctype>. Docs are here
return is not a function call and it's better to write return ch; than return(ch);
if (ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X'){ return true; } else { return false; } is completely equivalent to the shorter return ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X';
Also take a look at system(“pause”); - Why is it wrong?
Happy coding! Let me know if questions remain
I have a small problem here. This portion of code does not break the loop when the condition has been met. It is supposed to skip the loop if the user enters 'N', and to break if the user enters 'N' after each new loop prompt. Otherwise, it is the indefinitely loop with each input of 'Y'.
#include <iostream>
using namespace std;
void text();
char text()
{
char choice;
cout << "Enter Y/N: " << endl;
cin >> choice;
return choice;
}
int main()
{
text();
while(text() == 'Y' || text() == 'y')
{
text();
if(text() == 'N' || text() == 'n') {break;}
}
system("pause");
return 0;
}
The problem with the code is that you run text() function in every check, asking for input, the solution would be to store the result from text() into another variable like below:
#include <iostream>
using namespace std;
void text();
char text()
{
char choice;
cout << "Enter Y/N: " << endl;
cin >> choice;
return choice;
}
int main()
{
char choice;
choice = text();
while(choice == 'Y' || choice == 'y')
{
choice = text();
if(choice == 'N' || choice == 'n') {break;}
}
system("pause");
return 0;
}
The following will suffice:
#include <iostream>
int main(){
char choice = 'y';
while (std::cin && ::tolower(choice) == 'y'){
// do work
std::cout << "Enter Y/N: ";
std::cin >> choice;
}
}
If you insist on using a function then a simple void function with an argument passed by reference will do:
#include <iostream>
void choicefn(char& c){
std::cout << "Enter Y/N: " << std::endl;
std::cin >> c;
}
int main(){
char choice = 'y';
while (std::cin && ::tolower(choice) == 'y'){
// do work
choicefn(choice);
}
}
If you want to be really pedantic then modify the while statement to:
while (std::cin && ::tolower(choice) == 'y' && ::tolower(choice) != 'n')
Simply save the entered char in a char variable
char e = text();
while(e== 'Y' || e== 'y')
{
choice = text();
if(e== 'N' || e== 'n')
break;
}
Also erase the: void text();
You can't have two functions with the same name or one might say, can not overload functions distinguished by return type alone.
Start of the program you need to input how many elements you want for example if selected 3 you can type a b c but if you input more than 3 elements a b c d the program instantly crashes.
Haven't figured out how to make if you input the more than 4 element a b c d it will only read the a b c part.
#pragma hdrstop
#pragma argsused
#include <string>
#include <tchar.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
#include <iostream.h>
#include <iomanip>
#include <sstream>
int main() {
char teikums[100]; // Masiva lielums
int c, i, count, patsk; // Patskani
char yesno; // Atkartosanas Mainigais
do {
system("cls"); // Notira Ekranu
patsk = 0; // Pieskir vertibu
cout << "Ievadi Massiva lielumu 1-100: ";
cin >> count;
if (count > 100 || count < 1) {
cout << "Massivs nedriklst but lielaks par 100 vai mazaks par 0";
}
else {
cout << "Ievadi " << count << " burtus vienu pa vienam\n";
for (i = 1; i <= count; i++) {
cin >> teikums[i];
}
cout << "\nIzmantotie Patskani:";
for (i = 0; teikums[i] != '\0'; i = i + 2) {
if (teikums[i] == 'a' || teikums[i] == 'e' ||
teikums[i] == 'o' || teikums[i] == 'o' ||
teikums[i] == 'u' || teikums[i] == 'A' ||
teikums[i] == 'E' || teikums[i] == 'I' ||
teikums[i] == 'O' || teikums[i] == 'U') {
++patsk;
cout << teikums[i];
}
}
cout << "\nPatskanu Skaits: " << patsk;
}
cout << ("\nVai velaties atkartot(Y/cits):");
// prasa lietotajam vai velas atkartot
cin >> yesno;
if (yesno == 'y' || yesno == 'Y') {
}
else {
return 0;
}
}
while (tolower(yesno) != 'n');
getch();
}
Your program will not behave as you expect if you enter in more numbers than your count because of how it is parsing the inputs.
for (i = 1; i <= count; i++) {
cin >> teikums[i];
}
Let's say your count is 1, and you enter in 1 2.
This will loop once and say teikum[1] to be 1, and 2 is still leftover waiting to be grabbed by an input stream. Below that you have,
cin >> yesno;
which will now set yesno to be 2 and your program will terminate because 2 != 'n'. You will need to either input the data correctly as your format expects or clear cin using something like cin.ignore('\n') which will ignore the current line of input.
Further, you start your i at 1 and go up to count but your array is only size 100. If count is 100, it will try to access teikum[100] which will be out of bounds as your array goes from 0 - 99
I made a little game where the program jumbles up a word and asks for player input. However, one of the If statements are giving me an error and stopping me from compiling the program.
string isready;
cin >> isready;
if (isready == 'y' || 'Y')
Above I set up a string to be called isready, than asked the user for input. As seen above,
I wanted the if statement to activate if either y or capital y was typed in and received.
However, it just gives me the error:
invalid operands to binary expression ('string'
(aka 'basic_string, allocator >') and 'int')
Perhaps I'm missing a #include file?
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <unistd.h>
using namespace std;
int main()
{
enum fields {WORD, HINT, NUM_FIELDS};
const int NUM_WORDS = 5;
const string WORDS[NUM_WORDS][NUM_FIELDS] = //5x2 array
{
{"wall", "Do you feel you're banging your head against something?"},
{"glasses", "These might help you see the answer."},
{"labored", "Going slowly, is it"},
{"persistent", "Keep at it."},
{"jumble", "It's what the game is all about."}
};
srand(static_cast<unsigned int>(time(0)));
int choice = rand() % NUM_WORDS;
//Choice value in array, than area in array where word and hint are
string theWord = WORDS[choice][WORD]; //word to guess
string theHint = WORDS[choice][HINT]; //hint for word
string jumble = theWord; //jumbled version of word
int length = jumble.size();
//Index1 and index2 are random locations in the string theWord
//last two lines swaps areas, ending the for function with a different
//jumble variable every time.
for (int i = 0; i < length; ++i)
{
int index1 = rand() % length;
int index2 = rand() % length;
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
cout << "\t\tWelcome to Word Jumble!\n\n";
cout << "Unscramble the letters to make a word.\n";
cout << "\n\n\nReady? (y/n)";
//I'm asking here if the player is ready
string isready;
cin >> isready;
if (isready == 'y' || 'Y')
{
cout << "Ok this is how the scoring works\n";
cout << "The length of the word you will guess is times by 5000.\n";
cout << "If you ask for a hint, your score will go down by half.\n";
cout << "If you get the wrong answer, your score will go down by 1000.";
cout << "\nOk, lets start!\n\n\n";
int counter = 3;
for(int i = 0; i < 3; ++i)
{
cout << counter << "..." << endl;
counter--;
}
sleep(1);
}
else
{
cout << "check";
}
cout << "Enter 'quit' to quit the game.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "The jumble is: " << jumble;
//Score system
unsigned long int score;
int amount_of_guesses, amount_of_wrong = 0;
string guess;
cout << "\n\nYour guess: ";
cin >> guess;
while ((guess != theWord) && (guess != "quit"))
{
if (guess == "hint")
{
cout << theHint;
amount_of_guesses++;
}
else
{
cout << "Sorry, that's not it.";
amount_of_wrong++;
}
cout << "\n\nYour guess: ";
cin >> guess;
}
score = theWord.length() * 1000 -(amount_of_wrong * 1000)
/ 2 * amount_of_guesses;
if (guess == theWord)
{
cout << "\nThat's it! You guessed it!\n";
}
cout << "Your score is: " << score;
cout << "\nThanks for playing.\n";
return 0;
}
here
(isready == 'y' || 'Y')
you are trying to use operator== on std::string and char, because 'y' is char. Apart from this conditions should be in parenthesis because || has lower precedence than ==
Correct version is:
( (isready == "y") || ( isready == "Y")) // use bool operator==
(const string& lhs,
const string& rhs);
Operator || takes logical expressions on both sides:
if (isready == "y" || isready == "Y")
Note the double quotes above, because isready is a std::string. You could also change isready to char, and use character constants (i.e. 'y' and 'Y' in single quotes).
Your current expression is syntactically valid, but it will be evaluated as unconditional true, because it is interpreted as follows:
if (isready == 'y' || 'Y' != 0)
// ^^^^^^^^
// != 0 part is implicit;
// `Y` != 0 is always true, so the entire OR is also always true
Change this statement
if (isready == 'y' || 'Y')
to
if ( isready == "y" || isready == "Y")
Take into account that there are double quotes.
The problem is that there is no such operator == that can compare an object of type std::string with an object of type char. There is no such a constructor in class std::string that could convert implicitly an object of type char to an object of type std::string. However class std::string has a constructor that can convert a string literal to an object of type std:string. So the right operand that is "y" or "y" is implicitly converted to a temporary object of type std::string. As the result in the condition above two objects of type std::string are compared.
Also the condition you wrote initially is invalid even if you would use string literals instead of character literals. If for example isready == "y" was equal to false then you will get
false || "y"
In this expression string literal "y" is converted to a pointer to its first character. As this pointer is not equal to NULL then the whole expression will be true independing of the value in isready
(isready == 'y' || 'Y')
You should check for each character seperately.
((isready == "y" || (isready == "Y"))
if (isready == 'y' || 'Y')
should be
if (isready == "y" || isready == "Y")