So I'm working on building a calculator that mimics the ones we use everyday. What I have shown is the logic within my function.
Previously when I had my cout lines (deleted, not shown anymore) to see if my "y" was being correctly stores, and my two variables, finalNum1 & 2, everything was working, but when going back, trying to add new cout lines, nothing prints. If there are more issues, feel free to point them out, but this code is unfinished, my main concern is nothing is printing, I understand this code still needs work. If anyone can help that'd be greatly appreciated!
int Calculator::calculate()
{
if (userInput[0] != 'q' || 'Q') // Checks for user input "Quit" or "quit"
{
int stringSize;
std::cin >> userInput; // User Input
stringSize = userInput.length();
int y = 0;
while (y < stringSize)
{
if (isdigit(userInput[y]))
{}
else
{
posi = y;
}
y++;
}
first = userInput.substr(0,posi);
second = userInput.substr(posi+1,y);
finalNum1 = std::stoi(first); // Sigbart error
finalNum2 = std::stoi(second);
std::cout << finalNum1 + finalNum2; // won't print
switch (userInput[posi])
{
case '+':
std::cout << finalNum1 + finalNum2;
break;
case '-':
std::cout << finalNum1 - finalNum2;
break;
case '*':
std::cout << finalNum1 * finalNum2;
break;
case '/':
std::cout << finalNum1 / finalNum2;
break;
case '%':
std::cout << finalNum1 % finalNum2;
break;
}
}
else
std::cout << "Goodbye";
return 0;
}
For printing integer it is easier if you cast them to string.
using namespace std;
float tmp = finalNumber1 + finalNumber2;
string out = to_string(tmp);
cout << tmp << endl;
Then another thing. You should use for instead of while.
Related
I'm making a game that tests the ASCII strength of a user versus a bot. (There is also a 2 player mode but that's working fine.) The full description is given at the top of my .cpp file. As a basic breakdown, the bot opens a txt file with 500 common four letter words and inserts them into a size 500 array. It then randomly generates a number to pick a random one, and then goes through the process of tovalue() to recieve its ASCII value, where in tovalue() runs through chartoint() four times, one for each character of the word. My issue is that the program calculates the ASCII value perfectly fine of the user generated word, but always returns 0 (0000) for the botword, no matter what the word.
I've tried a few iterations of the generateword() function including using a vector but always get the same resutls. I've done a lot of digging about this and haven't quite found any solutions, although I suspect that the chartoint() function could be better optimized, just not sure how to impliment any better solutions for this specific case. Also, don't think the problem is with chartoint() since it works fine for user input, but I'm pretty sure the problem is with generateword(). Suggestions for making chartoint() would be helpful, but its not my main priority right now since I just need the program to 100% work first. Also, I've confirmed that all of the words in my .txt file are all caps and only four characters per line.
// Write the code for a game called “ASCII Strength” of a four-letter word selected by Player 1
// followed by a four-letter word selected by Player 2. The result would be the sum
//of the ASCII value of each of the letters of the selected words and whoever has higher sum (called ASCII strength) wins.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;;
int chartoint(char a) {
switch (a) {
case 'A':
return 1;
break;
case 'B':
return 2;
break;
case 'C':
return 3;
break;
case 'D':
return 4;
break;
case 'E':
return 5;
break;
case 'F':
return 6;
break;
case 'G':
return 7;
break;
case 'H':
return 8;
break;
case 'I':
return 9;
break;
case 'J':
return 10;
break;
case 'K':
return 11;
break;
case 'L':
return 12;
break;
case 'M':
return 13;
break;
case 'N':
return 14;
break;
case 'O':
return 15;
break;
case 'P':
return 16;
break;
case 'Q':
return 17;
break;
case 'R':
return 18;
break;
case 'S':
return 19;
break;
case 'T':
return 20;
break;
case 'U':
return 21;
break;
case 'V':
return 22;
break;
case 'W':
return 23;
break;
case 'X':
return 24;
break;
case 'Y':
return 25;
break;
case 'Z':
return 26;
break;
}
return 0;
}
int tovalue(string input) {
int first = chartoint(input[0]);
int second = chartoint(input[1]);
int third = chartoint(input[2]);
int fourth = chartoint(input[3]);
cout << first << second << third << fourth; // EXISTS TO TEST CALCULATION
int value = first + second + third + fourth;
return value;
}
string generateword() {
string arr[500];
ifstream file("words.txt");
if (file.is_open())
{
for (int i = 0; i < 500; i++) {
string temp;
getline(file, temp);
arr[i] = temp;
}
file.close();
}
else
{
cout << "Error: Unable to open file.";
exit(0);
}
srand(time(0));
int random_index = rand() % 500;
string random_word = arr[random_index];
return random_word;
}
int main()
{
cout << "Welcome to ASCII strength, a game where the strongest word wins!";
cout << "\nTo play, you must enter a four letter word. The program will calculate the 'ASCII strength' of your word and compare it to your opponent.";
cout << "\nWhoever has the higher sum will win!";
char another;
another = 'y';
while (another == 'y' || another == 'Y') {
cout << "\nWould you like to play against a friend, or against a bot? (F/B)";
char mode;
cin >> mode;
if (mode == 'F' || mode == 'f') {
cout << "\nPlayer 1, please input your four letter word in all caps: ";
string answer1;
cin >> answer1;
int value1;
value1 = tovalue(answer1);
cout << "\nPlayer 2, please input your four letter word in all caps: ";
string answer2;
cin >> answer2;
int value2;
value2 = tovalue(answer2);
if (value1 > value2) {
cout << "\nPlayer 1 wins!";
}
else if (value2 > value1) {
cout << "\nPlayer 2 wins!";
}
else if (value1 == value2) {
cout << "\nTie!";
}
}
else if (mode == 'B' || mode == 'b') {
cout << "\nPlease input your four letter word in all caps: ";
string answer;
cin >> answer;
int valueanswer;
valueanswer = tovalue(answer);
string botword;
botword = generateword();
cout << "\nThe bot generates a random word based on a list of popular four letter words.";
cout << "\nThe bot has generated this word: " << botword;
int valuebot;
valuebot = tovalue("botword");
cout << valueanswer << " " << valuebot; // THIS EXISTS PURELY TO TEST WHETHER THE VALUES ARE PROPERLY CALCULATING
if (valueanswer > valuebot) {
cout << "\nYou win!";
}
else if (valuebot > valueanswer) {
cout << "\nThe bot wins!";
}
else if (valueanswer == valuebot) {
cout << "\nTie!";
}
}
cout << "\nWould you like to start a new game? (y/n)";
cin >> another;
}
}
Your problem is this line:
valuebot = tovalue("botword");
Since all characters in "botword" are lowercase, you get all 0 score. You probably meant to write
valuebot = tovalue(botword);
bjarne stroustrup chapter 6 calculator.cpp. I have edited part of the program.
Ss it possible for the "at plus" to loop back to the "hey" without executing the break statement?
When I tried to calculate:
3
+
3
+
3
+
3
;
I am confused how did the "at plus" loop back to the "hey" at the case '+'. I added the "at plus" and "hey" to try to know the flow of the statement.
// deal with + and -
double expression()
{
cout << "expression" << endl;
double left = term(); // read and evaluate a Term
cout << "welcome to expression()" << endl;
Token t = ts.get(); // get the next token from token stream
cout << "still at expression()" << endl;
while (true) {
switch (t.kind) {
case '+':
cout << "hey" << endl;
left += term(); // evaluate Term and add
t = ts.get();
cout << "at plus" << endl;
break;
case '-':
left -= term(); // evaluate Term and subtract
t = ts.get();
break;
default:
ts.putback(t); // put t back into the token stream
return left; // finally: no more + or -: return the answer
}
}
}
The break statement can be somewhat confusing, because it can be used in a couple of different ways. Basically, it operates on the innermost thing that it could apply to. So those break statements that are inside the switch statement end the processing of the current case. That's all. A break statement outside the switch statement would end the loop:
void f() {
while (true) {
std::cin >> x;
switch(x) {
case 1:
do_someting();
break; // inside switch, so exits **this case**
case 2:
do_someting();
break; // inside switch, so exits **this case**
}
break; // outside switch, inside while, so exits while
}
std::cout << "done\n";
}
You missing code so I made example,
remember it's usually bad practice, the code in case should be easy and readable.
all you need to do is wrap the code you want to be executed more then once inside for/while loop, keep in mind break outside of the loop.
#include <iostream>
using namespace std;
int main()
{
int j = 1;
int k = 1;
while(k > 0){
switch(j){
case 1:
for (int i =0; i <= 2; i ++){
cout << "hey " << endl;
cout << "bye " << endl;
}
k--;
break;
case 2:
//execute this code
break;
}
}
}
output: hey bye hey bye hey bye
how do I run only one of those if statements in a for loop? For example i have an input of 5...and i just want it to print five...but whenever i run this code, it will execute all if statement..please help me
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
// Complete the code.
int a;
int b;
cin >> a;
for (a = 0; 0<a<10; a++)
{
if (a == 1)
{
cout << "one";
}
if (a == 2)
{
cout << "two";
}
if (a == 3)
{
cout << "three";
}
if (a == 4)
{
cout << "four";
}
if (a == 5)
{
cout << "five";
}
if (a == 6)
{
cout << "six";
}
if (a == 7)
{
cout << "seven";
}
if (a == 8)
{
cout << "eight";
}
if (a == 9)
{
cout << "nine";
}
else if (a > 9 && a%2 == 0)
{
cout << "even";
}
else if (a > 9 && a&2 != 0)
{
cout << "odd";
}
}
return 0;
}
The problem seems to be the for loop. Your program accepts a value for a as an input, but then as soon as the loop begins, it resets the value of a to 0 (for (a = 0;...
Therefore it's looping 10 times, and on each loop a will have a different value, starting from 0 and ending at 9. This means that all of your if statements will get hit at some point in the execution, generally one on each of the loops round the for.
To get your expected behaviour " input of 5...and i just want it to print five", simply remove the for loop from your code.
Your unnecessary for loop trashes the input value of a and loops forever! (At least until you overflow your signed type a).
You are replacing a by using it as the counter in the for loop! If you only ever want one output, then drop the for loop completely. If your for loop were to remain then your expression 0 < a < 10 ought to be recast as 0 < a && a < 10 : formally 0 < a < 10 is evaluated as (0 < a) < 10 which is either true < 10 or false < 10 which is always true.
Also consider refactoring your if else to set up explicitly mutually exclusive statements:
if (a == 1){
cout << "one";
} else if (a == 2){
cout << "two";
/*and so on*/
} else {
/*all other cases*/
}
Although in this case you might want to consider a switch block:
switch (a){
case 1:
cout << "one";
break; // to stop program control flowing into the next case
case 2:
cout << "two";
break;
/*and so on*/
default:
/*all other cases*/
}
if () {
} else if () {
}
Although,
switch() {
}
will be more efficient in your case.
Update 1
#Aleph0
Below is the solution
int main() {
int a;
cin >> a;
switch (a) {
case 1: cout << "one"; break;
case 2: cout << "two"; break;
case 3: cout << "three"; break;
case 4: cout << "four"; break;
case 5: cout << "five"; break;
case 6: cout << "six"; break;
case 7: cout << "seven"; break;
case 8: cout << "eight"; break;
case 9: cout << "nine"; break;
default: cout << ((a & (1 << 31)) ? "negative" : (a & 1) ? "odd" : "even"); break;
}
}
Question has been asked to do following
i have an input of 5...and i just want it to print five
And, someone has correctly mentioned above, for loop is immaterial here.
First up, yes, this is homework that I'm struggling with, so help would be appreciated. We're making a calculator in C++ that is supposed to function differently on the + and - operators.
With '+' it is supposed to to add the two numbers together (i.e., 45 + 54 = 4554).
With '-' it is supposed to remove the first digit of the first element from the second element (i.e., 1217 - 1 = 27) We're supposed to do this by overloading the + and - operators, which I seem to be struggling with. Thanks in advance for the help!
class WhackyRPN
{
public:
int value;
int operator+ (WhackyRPN a[]);
int operator- (WhackyRPN s[]);
int getValue();
void setValue(int);
};
void WhackyRPN::setValue(int val){
value = val;
}
int WhackyRPN::getValue(){
return value;
}
int WhackyRPN::operator+ (WhackyRPN a[]){
string combinedNum = to_string(a[1].getValue()) + to_string(a[0].getValue());
int finalNum = stoi(combinedNum);
return finalNum;
}
int WhackyRPN::operator- (WhackyRPN s[]){
int minusNum;
string firstNum = to_string(s[0].getValue());
string secondNum = to_string(s[1].getValue());
string minusString = to_string(minusNum);
for (int i = 0; i < firstNum.length(); i++){
if (firstNum.at(0) != secondNum.at(i)){
minusString.at(i) += secondNum.at(i);
}
}
minusNum = stoi(minusString);
return minusNum;
}
int main()
{
WhackyRPN stackPos[4];
string indent = " ";
string userInput;
stackPos[0].setValue(0);
stackPos[1].setValue(0);
stackPos[2].setValue(0);
stackPos[3].setValue(0);
while (1){
system("cls");
cout << "---STACK---" << endl;
cout << indent << stackPos[3].getValue() << endl;
cout << indent << stackPos[2].getValue() << endl;
cout << indent << stackPos[1].getValue() << endl;
cout << indent << stackPos[0].getValue() << endl;
cout << "CMD: ";
cin >> userInput;
if (userInput == "exit" || userInput == "Exit" || userInput == "EXIT"){
exit(0);
}
switch (userInput[0]){
case 'q':
case 'Q':
exit(0);
case 'p':
case 'P':
stackPos[0] = stackPos[1];
stackPos[1] = stackPos[2];
stackPos[2] = stackPos[3];
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
stackPos[3].setValue(stackPos[2].getValue());
stackPos[2].setValue(stackPos[1].getValue());
stackPos[1].setValue(stackPos[0].getValue());
stackPos[0].setValue(stoi(userInput));
break;
case '+': //combine pos[1] and pos[0];
int finalNum = stackPos[1] + stackPos[0];
stackPos[3].setValue(stackPos[2].getValue());
stackPos[2].setValue(stackPos[1].getValue());
stackPos[1].setValue(stackPos[0].getValue());
stackPos[0].setValue(finalNum);
break;
case '-': //remove pos[0].firstNum from pos[1]
int minusNum = stackPos[0] - stackPos[1];
stackPos[3].setValue(stackPos[2].getValue());
stackPos[2].setValue(stackPos[1].getValue());
stackPos[1].setValue(stackPos[0].getValue());
stackPos[0].setValue(minusNum);
break;
case '/': //divide pos[1] by pos[0]
if (stackPos[0].getValue() == 0){
cout << "Cannot divide by 0" << endl;
system("pause");
break;
}
int endQuotient = stackPos[1].getValue() / stackPos[0].getValue();
stackPos[3].setValue(stackPos[2].getValue());
stackPos[2].setValue(stackPos[1].getValue());
stackPos[1].setValue(stackPos[0].getValue());
stackPos[0].setValue(endQuotient);
break;
case '*': //multiply pos[1] by pos[0]
int endProduct = stackPos[1].getValue() * stackPos[0].getValue();
stackPos[3].setValue(stackPos[2].getValue());
stackPos[2].setValue(stackPos[1].getValue());
stackPos[1].setValue(stackPos[0].getValue());
stackPos[0].setValue(endProduct);
break;
default:
break;
}
}
system("pause");
return 0;
}
You get the error that you do because there really is no overload of operator+ which stackPos[1] + stackPos[0] could resolve to. The only overload you have is of type WhackyRPN::operator+(WhackyRPN*);(it is a pointer even though you have written an array - read here and here. But that isn't relevant to this question.) The signature should be WhackyRPN::operator+(WhackyRPN). More idiomatic would be WhackyRPN::operator+(const WhackyRPN&). For more, read this great answer.
replace
int finalNum = stackPos[1] + stackPos[0];
with
int finalNum = stackPos[1].getValue() + stackPos[0].getValue();
In your program, you have the array of objects stackPos[], which has functions setValue() and getValue() which take and return integer respectively. You need to use getValue() here as the array elements themselves are not integer, they are objects.
This is exactly what your error statement is saying as well. But you seem to already know that because you have implemented it in * and / operations.
Hope this helps.
Having some trouble with some code and I cannot get to the bottom of it. This code:
int main()
{
int choice;
while (choice != -1)
{
system("cls");
std::cout << "Main Menu: " << std::endl
<< " 1. Encode." << std::endl
<< " 2. Decode." << std::endl
<< "-1 to exit." << std::endl;
std::cin >> choice;
switch (choice)
{
case 1:
encode();
break;
case 2:
decode();
break;
case -1:
break;
}
}
getchar();
return 0;
}
void encode()
{
std::string plainText;
std::string encText = "Test";
std::cout << "Enter text to be encrypted.\n";
getline(std::cin, plainText);
for (int x = 0; x < plainText.length(); x++)
{
//encText += plainText.substr(x, x + 1);
}
std::cout << encText;
getchar();
return;
}
If I enter '1' at the first cin >> choice, I go into encode(), once there, entering any text causes the program to go back to the while, perform system("cls"), and then jumps right back to "Enter text to be encrypted." down in encode().
Any help? I'm clueless.
If you'd like to exit your while loop after encode() or decode(), you have to satisty the while's condition. You can do this by simple setting choice to -1 after the function calls:
case 1:
encode();
choice = -1;
break;
case 2:
decode();
choice = -1;
break;
Just so you're aware, the return at the end of encode() causes the encode() function to finish, not main. That line of code actually does nothing; since there's nothing after it, it would happen anyway.