C++ Boolean function returning 56 - c++

I have a function to return a bool:
bool restart()
{
std::string answer;
bool answered = false;
while(answered == false)
{
cout << endl << endl << "Do you want to play again? y/n : ";
cin >> answer;
if(answer == "y" || answer == "Y" || answer == "1" || answer == "yes")
{return true;}
if(answer == "n" || answer == "N" || answer == "0" || answer == "no")
{return false;}
}
}
When I call it using:
cout << restart();
I get the output:
Do you want to play again? y/n : y
56
Can anyone see how to fix this strange problem?
Thanks in advance.
My WIP code as it is now:
#include <iostream>
#include <cstdlib>
using namespace std;
void drawScreen(int grid[3][3]); //
int movef(int grid[3][3], bool playersMove);
int updateGrid(int grid[3][3], int move, bool playersMove);
bool hasWon(int grid[3][3]);
bool swapMover(bool playersMove); //
bool restart();
void endGame();
int main()
{
int grid[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
bool appRunning = true, gameRunning = true, playersMove = true;
int move;
// tests //
std::cout << restart();
// tests //
//while(appRunning == true)
//{
// while(gameRunning == true)
// {
// drawScreen(grid);
// move = movef(grid, playersMove);
// grid[3][3] = updateGrid(grid, move, playersMove);
// drawScreen(grid);
// gameRunning = hasWon(grid);
// playersMove = swapMover(playersMove);
// }
// appRunning = restart();
//}
//endGame();
}
void drawScreen(int grid[3][3])
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(grid[i][j] == 10){cout << "X ";if(j == 2){cout << endl << endl;}}
if(grid[i][j] == 11){cout << "O ";if(j == 2){cout << endl << endl;}}
if(grid[i][j] != 10 && grid[i][j] != 11){cout << grid[i][j] << " ";
if(j == 2){cout << endl << endl;}}
}
}
}
int movef(int grid[3][3], bool playersMove)
{
return 0;
}
int updateGrid(int grid[3][3], int move, bool playersMove)
{
return 0;
}
bool hasWon(int grid[3][3])
{
return false;
}
bool swapMover(bool playersMove)
{
if(playersMove == true){return false;}
if(playersMove == false){return true;}
}
bool restart()
{
std::string answer;
bool answered = false;
while(answered == false)
{
cout << endl << endl << "Do you want to play again? y/n : ";
cin >> answer;
if(answer == "y" || answer == "Y" || answer == "1" || answer == "yes")
{return true;}
if(answer == "n" || answer == "N" || answer == "0" || answer == "no")
{return false;}
}
}
void endGame()
{
}

[This is somewhat of a repost of my comment since OP said it solved his problem]
You have no return value defined outside of the while loop. If somehow you get outside of it, you do not return a value (though I have no idea what behavior is expected or even if any behavior is expected in this case)
To make my answer a bit more thorough, I have found this:
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?

OK, I'm making a guess. Your original code has the line
grid[3][3] = updateGrid(grid, move, playersMove);
And your grid definition is
int grid[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
This means that your are writing out of the array bounds. This is undefined behavior.
Please correct this and check if your program works as expected.

I used the mingw32 compiler, when using g++ 4.8 it works fine. It seems to be a compiler error. (thanks to grizzly)

Related

executing ls command and printing output it

so i have made this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
while(true)
{
string x;
string y;
string an1[3] = {"quit","exit","leave"};
double ver = 0.1;
cout << "basic0.1% ";
cin >> x;
if (x == "upgrade")
{
system("yay -Syyu");
}
else if (x == "install")
{
cout << "What do you want to install?" << "\n";
cin >> y;
system(("sudo yay -S " + y).c_str());
}
else if (x == "version")
{
cout << "version: " << ver << "\n";
}
else if (x == "clear")
{
system("clear");
}
else if(x == "quit" || "leave" || "exit")
{
break;
}
else if(x == "ls")
{
}
}
return 0;
}
and in the else if(x == "ls"){} i wanted to show the output of the command,i tried putting system("ls");
but it just exits the program.
btw this should be a little terminal emulator for linux but i am not sure yet,i am just having some fun.
system("ls"). works fine. Your problem is this:
else if(x == "quit" || "leave" || "exit")
{
break;
}
Let's say you type ls. Then x contains the string "ls". x == "quit" is false because you didn't type quit. "leave" is true because it's a non-null pointer. "exit" is true because it's a non-null pointer. false || true || true is true, so the program quits.

How do I remove zeros between my outputs? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
bool getAnswer(int a);
int main ()
{
string questions[5] = {"CPU stands for 'Central Processing Unit'", "RAM stands for 'Reserved Access Main'", "HDD stands for 'Hard Drive Doubler'", "SSD stands for 'Solid State Drive'", "CPP stands for 'C Programming Plus'"};
for (int i = 0; i < 5; i++)
{
cout << "Question " << ++i << " \n";
i--;
cout << questions[i] << "\n";
cout << getAnswer(i) << endl;
}
}
bool getAnswer(int a)
{
bool answer[5] = {true, false, false, true, false};
bool user[5];
string input;
cout << "Answer " << ++a << " \n";
a--;
cout << "Enter a true or false answer: " << "\n";
cin >> input;
while (input != "T" && input != "t" && input != "F" && input != "f" && input != "True" && input != "true" && input != "False" && input != "false")
{
cout << "Invalid entry, try again!\nEnter a true or false answer: " << "\n";
cin >> input;
}
if (input == "T" || input == "t" || input == "True" || input == "true")
{
user[a] = true;
}
else if (input == "F" || input == "f" || input == "False" || input == "false")
{
user[a] = false;
}
if (answer[a] == user[a])
{
cout << "Correct!\n";
}
else if (answer[a] != user[a])
{
cout << "Incorrect!\n";
}
}
In the output between the correct/incorrect and next question, I keep getting a "0" in-between. How do i remove them.
Ex:
Question 1
CPU stands for 'Central Processing Unit'
Answer 1
Enter a true or false answer:
f
Incorrect!
0
Question 2
RAM stands for 'Reserved Access Main'
Answer 2
Enter a true or false answer:
t
Incorrect!
0
Just remove cout << "correct" and cout << "incorrect" and change the return type from bool to std::string.
From:
bool getAnswer(int a) {
...
if (answer[a] == user[a])
cout << "Correct!\n";
else if (answer[a] != user[a])
cout << "Incorrect!\n";
}
To:
std::string getAnswer(int a) {
...
if (answer[a] == user[a])
return "Correct!\n";
else if (answer[a] != user[a])
return "Incorrect!\n";
}
What happens in you program is that your function prints on the screen the answer (as that is what your function does inside the last two ifs). After that, your program tries to print what your function returns through:
cout << getAnswer(i) << endl;
Now, you declared the return value of getAnswer()to be of type bool but, actually, you did not specified a return statement. Consequently, the value returned by your function can be either 1 or 0 (undefined behaviour), in your case it is 0, the value you see.
Tip
Use std::cout instead of cout. See Why is “using namespace std” considered bad practice?
You declared getAnswer() to return a bool value, but never return anything. One way to fix your output is to honor this return type and change
if (answer[a] == user[a])
{
cout << "Correct!\n";
}
else if (answer[a] != user[a])
{
cout << "Incorrect!\n";
}
to
return answer[a] == user[a];
Then instead of
cout << getAnswer(i) << endl;
do
if (getAnswer(i)) {
cout << "Correct!\n" << endl;
} else {
cout << "Incorrect\n" << endl;
}
your problem lies with the return value of the getAnswers
cout << getAnswer(i) << endl;
you are already outputting if the answer is correct or not within the getanswer function. and again you are using cout to output the return value of the getAnswer
you can either :
cout << "Question " << ++i << " \n";
i--;
questions[i]
getAnswer(i);
cout << endl;
or you can simply stop doing the output in getAnswer and return a string to containing the message.
std::string getAnswer(int a)
{
bool answer[5] = {true, false, false, true, false};
bool user[5];
string input;
...
...
...
if (answer[a] == user[a])
{
input = "Correct!\n";
}
else if (answer[a] != user[a])
{
input = "Incorrect!\n";
}
return input;
}
if you do it like that you don't need to change anything in your main. make sure to change the decleration of the getAnswers from
bool getAnswer(int a);
to
std::string getAnswer(int a);

How to check every character in string?

The program will ask user to input strand which has to be composed of only ABCD and if the input contains letter other than ABCD it must show error, otherwise it should output "ok!"
string strand1;
again:
cout << "Enter String 1:\n";
cin >> strand1;
for (int i = 0; i <= strand1.length(); i++)
{
if (strand1.at(i) != 'A'&&strand1.at(i) != 'B'&&strand1.at(i) != 'C'&&strand1.at(i) != 'D')
{
cout << "Invalid Input";
system("cls");
goto again;
}
else
{
i++;
}
}
cout << "ok";
_getch();
return 0;
Move the necessary checks to a function -- isValidInput.
Use hand coded logic to check whether the input is valid or use the standard library function std::find_if to do the same.
Use the function in a while loop in the main function.
bool isNotABCD(char c)
{
return !((c == 'A') || (c == 'B') || (c == 'C') || (c == 'D'));
}
bool isValidInput(std::string const& str)
{
return (std::find_if(str.begin(), str.end(), isNotABCD) == str.end());
}
int main()
{
string strand1;
cout << "Enter String 1:\n";
while ( cin >> strand1 && !isValidInput(strand1) )
{
cout << "Invalid Input";
system("cls");
cout << "Enter String 1:\n";
}
cout << "ok";
}
Update
You can also use a simpler version of isValidInput(), Thanks to #Blastfurnace for the suggestion.
bool isABCD(char c)
{
return (c == 'A') || (c == 'B') || (c == 'C') || (c == 'D');
}
bool isValidInput(std::string const& str)
{
return (std::all_of(str.begin(), str.end(), isABCD));
}
Update 2
You can also use a still simpler version of isValidInput(), Thanks to #JorenHeit for the suggestion.
bool isValidInput(std::string const& str)
{
return (std::find_first_not_of("ABCD") == std::string::npos);
}
Your question is unclear, but after examining your code I believe the problem is that for your loop condition you are using i <= strand1.length when you should be using i < strand1.length.
The loop condition you are using will check an index out of bounds of the string. In addition, you should not be incrementing i in the else statement as that is already done in the for statement. In the future, please clearly state your question along with any error codes you are getting.

C++ Mathematical Expression Parser Issue

#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include "NodeType.h"
using namespace std;
// Test if token is an operator
bool isOperator(char token);
int getPrecedence(char token);
bool comparePrecedence(char tokenA, char tokenB);
int main()
{
stack<char> tokenStack;
queue<char> tokenQueue;
string expression= "", postfix= "";
char x;
cout<<"Please enter a mathematical expression: "<<endl;
getline(cin, expression);
cout<<expression.length()<<endl;
for(int i = 0; i <= expression.length(); i++)
{
x = expression[i];
if(isdigit(x))
{
tokenQueue.push(x);
}
if(isOperator(x))
{
while((!tokenStack.empty()) && (comparePrecedence(x, tokenStack.top() == true)))
{
char z = tokenStack.top();
tokenQueue.push(z);
tokenStack.pop();
}
tokenStack.push(x);
}
if(x == '(')
{
tokenStack.push(x);
}
if(x == ')')
{
while((!tokenStack.empty()) && (tokenStack.top() != '('))
{
char z = tokenStack.top();
tokenQueue.push(z);
tokenStack.pop();
}
tokenStack.pop();
}
while(!tokenStack.empty())
{
char z = tokenStack.top();
tokenQueue.push(z);
tokenStack.pop();
}
}
return 0;
}
int getPrecedence(char token)
{
if((token == '+') || (token == '-'))
{
return 1;
}
else if((token == '*') || (token == '/'))
{
return 2;
}
else if ((token == '(') || (token == ')'))
return 0;
else
return 99;
}
// Test if token is an operator
bool isOperator(char token)
{
return token == '+' || token == '-' ||
token == '*' || token == '/';
}
bool comparePrecedence(char tokenA, char tokenB)
{
if(getPrecedence(tokenA) < getPrecedence(tokenB))
return true;
else
return false;
}
For some reason I cannot get my code to work correctly. It always throws a
Thread 1: EXC_BAD_ACCESS (code=EXC_1386_GPFLT) error. It is also not correctly placing the '+' sign when I test using a simple string such as: (3+4).
The Queue should look like: 34+ but it hold 3+4. It seems to me that the '+' operator never gets pushed onto the stack. Can anyone please help me find what I should be focussing my attention on?
Debugging code is a valuable skill to learn, it's my opinion that it should form a much more important part of curricula in schools.
For example, if you modify your code to output all the stack and queue operations thus:
int main()
{
stack<char> tokenStack;
queue<char> tokenQueue;
string expression= "", postfix= "";
char x;
cout<<"Please enter a mathematical expression: "<<endl;
getline(cin, expression);
cout<<expression.length()<<endl;
for(int i = 0; i <= expression.length(); i++)
{
x = expression[i];
if(isdigit(x))
{
tokenQueue.push(x);
cout << "qpush A " << x << '\n';
}
if(isOperator(x))
{
while((!tokenStack.empty()) && (comparePrecedence(x, tokenStack.top() == true)))
{
char z = tokenStack.top();
tokenQueue.push(z);
cout << "spop G " << z << '\n';
cout << "qpush B " << z << '\n';
tokenStack.pop();
}
tokenStack.push(x);
cout << "spush E " << x << '\n';
}
if(x == '(')
{
tokenStack.push(x);
cout << "spush F " << x << '\n';
}
if(x == ')')
{
while((!tokenStack.empty()) && (tokenStack.top() != '('))
{
char z = tokenStack.top();
tokenQueue.push(z);
cout << "spop H " << z << '\n';
cout << "qpush C " << z << '\n';
tokenStack.pop();
}
cout << "spop I " << tokenStack.top() << '\n';
tokenStack.pop();
}
while(!tokenStack.empty())
{
char z = tokenStack.top();
tokenQueue.push(z);
cout << "spop J " << z << '\n';
cout << "qpush D " << z << '\n';
tokenStack.pop();
}
}
return 0;
}
and run it with a simple 3+4, you'll see the following output:
qpush A 3
spush E +
spop J +
qpush D +
qpush A 4
So you are placing the operation on the stack. However, you later take it off the stack and put it on the queue before you place the next digit on the queue.
That's definitely the wrong order but, if you examine the code, it's not just a small snippet that has two lines in the wrong order (that would be too easy).
The code that's doing that transfer from stack to queue is the final while loop in main() which, after every single character, transfers all the items from the stack to the queue, effectively rendering your stack superfluous.
That's where you should be looking but I'll give you a clue. You don't want to be transferring stack to queue after every character, only for those that involve numbers.
There may well be other problems after you solve that one but that method (debugging output every time you do something important) should be able to give you enough information to fix whatever comes along.

Writing a Taste test program for C++ not incrementing

I am writing a taste test program for a class and it will run fine up until my if statements. However, once I get into my if statements it isn't incrementing i, so it never leaves the while loop.
#include <iostream>
using namespace std;
void main()
{
int i = 0;
int q = 0;
int p = 0;
int c = 0;
char preference;
int x = 0;
cout << "How many taste tests would you like to do?" << endl;
cin >> x;
while (i<x)
{
cout << "Do you prefer Coke, Pepsi, or are they the same? Use c for coke, p for pepsi, and q for the same\n";
cin >> preference;
if (preference == 'q' || preference == 'Q')
{
q = q + 1;
i++;
}
if (preference == 'p' || preference == 'P')
{
p = p + 1;
i++;
}
if (preference == 'c' || preference == 'C')
{
c = c + 1;
i++;
}
}
if (p>q)
{
cout << "Pepsi wins" << endl;
if (c>p)
cout << "Coke wins" << endl;
if (c == p)
cout << "Tie" << endl;
}
}
I think that you are trying to check if the a determined char was clicked by cin >> preference but you are test int vars, so if i press 'q'
//if(preference==q || preference==Q) // 'q'==0 || 'p'==0
if(preference=='q' || preference=='Q') // 'q'=='q' || 'q'=='Q'
so add ''
I hope this helps
Change the following lines in the code for the expected behavior.
//if(preference==q || preference==Q)
if(preference=='q' || preference=='Q'
//if(preference==p || preference==P)
if(preference=='p' || preference=='P')
//if(preference==c || preference==C)
if(preference=='c' || preference=='C')