Can you add variables inside "cout" [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm new to C++, on the chapter 2 quiz of LearnCpp.com. I'm stuck and have a question. Can you add variables inside a std::cout statement? For example:
The program will not display my answer. The program ends as soon as the user presses enter after inputting the values. Thanks for your help ahead of time.
EDIT: Sorry for not posting the entire code. I'm also new to forums. I added the () like someone suggested. When I ran the program I think I saw it display the answer for a split second and it doesn't show that Press any key to continue. . .
#include "stdafx.h"
#include <iostream>
int main()
{
double first_value;
double second_value;
char user_operator;
std::cout << "Enter a double value: ";
std::cin >> first_value;
std::cout << "Enter a second double value: ";
std::cin >> second_value;
std::cout << "Enter one of the following (+, -, *, /): ";
std::cin >> user_operator;
if (user_operator == 43 || user_operator == 45\
|| user_operator == 42 || user_operator == 47)
switch (user_operator)
{
case 43:
std::cout << " " << (first_value + second_value) << "\n";
break;
case 45:
std::cout << " " << (first_value - second_value) << "\n";
break;
case 42:
std::cout << " " << (first_value * second_value) << "\n";
break;
case 47:
std::cout << " " << (first_value / second_value) << "\n";
break;
}
else std::cout << "Please enter a valid operator.";
return 0;
}

Yes, you can perform operations within a chain of std::ostream& operator<<(std::ostream&, T) calls. You just need to obey operator precedence and put parenthesis (()) around the expression to disambiguate in case it's necessary.
Here's a fixed Demo.

Related

Why does my code ignore a large chunk of itself? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
hey I've just started on a school project but can't figure out why the code just ignores a large chunk of itself.
(also the code is part of a function inside of "math.h")
ill paste the whole segment here so that debugging it is easier.
#include <iostream>
#include <chrono>
#include <thread>
#include <algorithm>
using namespace std;
using namespace chrono;
using namespace this_thread;
class math {
private:
unsigned short pts;
public:
unsigned short questAmount;
char diff;
short arrEasy[4] = {1, 2, 5, 10}, secondVar, ans, studAns;
void questProc() {
start:
cout << "How hard do you want the questtions to be?" << endl;
cout << "(The harder you choose, the larger the numbers you'll have to calculate)" << endl;
cout << "1) EASY" << endl;
cout << "2) MEDIUM" << endl;
cout << "3) HARD" << endl;
cout << "4) CALCULATOR MODE LOL" << endl << "~> ";
cin >> diff;
switch (diff) {
case '1':
system("cls");
cout << "EASY MODE ACTIVATED" << endl;
break;
case '2':
system("cls");
cout << "MEDIUM MODE ACTIVATED" << endl;
break;
case '3':
system("cls");
cout << "HARD MODE ACTIVATED" << endl;
break;
case '4':
system("cls");
cout << "CALCULATOR MODE ACTIVATED" << endl;
break;
default:
system("cls");
cout << "INPUTED VAL IS EITHER NOT AN INT OR ISN'T IN THE LIST"; //checks only the starting int ignores the rest...
sleep_for(0.5s); cout << "."; sleep_for(0.5s); cout << "."; sleep_for(0.5s); cout << "."; sleep_for(0.5s);
break;
if (diff != 1 && diff != 2 && diff != 3 && diff != 4) { goto start; }
}
// The following creates the question according to the set difficulty.
srand(time(NULL)); // Initializing random seed.
switch (diff) {
case 1: // Easy Mode:
system("cls");
random_shuffle(&arrEasy[0], &arrEasy[4]); // For first var.
secondVar = rand() % 10 + 1; // Rand number from 1 to 10 (for second var).
ans = arrEasy[0] * secondVar;
cout << arrEasy[0] << " * " << secondVar << " = ?" << endl << "~> ";
cin >> studAns;
break;
default:
break;
}
// The following checks if ans is correct.
if (studAns == ans) {
cout << "WELL DONE!";
}
else {
cout << "WRONG, CORRECT ANSWER WAS:" << ans;
}
}
};
I wanted it to continue on to actually calculate the question and to then check if I was right or not...
here's what I got instead:
How hard do you want the questtions to be?
(The harder you choose, the larger the numbers you'll have to calculate)
1) EASY
2) MEDIUM
3) HARD
4) CALCULATOR MODE LOL
~> 1
and then:
EASY MODE ACTIVATED
WELL DONE!
that's all it says, despite all the other things its also supposed to do...
ps. tell me if you need any more info.
Because of type mismatch!
you defined "diff" as a char and use it as such in your switch statement. However, in your second switch statement, you remove the quotes and use it as a number. That causes a char to int conversion according to the ascii table.
Look at the decimal field, the number 1 as an int corresponds to a non-printable character that you will rarely see in real life. The character '1' corresponds to 49.
Solution:
switch(diff){
case '1': //notice the quotations
//rest of code
break;
}
for this line
if (diff != 1 && diff != 2 && diff != 3 && diff != 4) { goto start; }
you mean
if (diff != '1' && diff != '2' && diff != '3' && diff != '4') { goto start; }
given that diff is a typed in char not an int

How I can make the program keep go next line after complete on if statement [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 5 years ago.
Improve this question
im trying to write a code but for some reason the program is stuck in a loop of the if statements
#include "std_lib_facilities.h"
int main()
{
double i = 0;
double u = 0;
cout << "Enter one numbers:\n";
while (cin >> i)
if (i > u)
{
cout << "the largest number is: " << i << '\n'
<< "the smallest number is " << u << "\n";
}
else if (i < u) {
cout << "the largest number is " << u << '\n'
<< "the smallest number is " << i << "\n";
}
else if (i == u) {
cout << "The numbers are equal\n";
}
cout << "blabla\n";
keep_window_open();
}
So my purpose is that after it checks the "if else" even is some of them true or not I need it to performe cout << "blabla\n";
the code is not finished, I just need to understand how to make it jump to another line so I will be able to keep write the continue.
If I understood you right, and you just need to print "blabla\n" every time inside the while loop, then you only need to put curly braces around, like this:
while (cin >> i) {
if (i > u) { ... }
else if (i < u) { ... }
...
cout << "blabla\n";
}
In general, you better write curly braces everywhere, because avoiding them saves you a second today but can steal an hour several months later, just in case you ever need to add something inside.
Note that you can also use goto construction to pass the execution of a program from any point to any other point, but you better don't use it because it is complex both to write and read.
If instead you just wanted to get one integer, then you should have used cin >> i; in place of your while loop.
Your problem is either not printing "blabla" while in the loop or not exiting the loop. For the latter see the answer by Ron.
For printing "blabla" while in the loop you need to make a block of the statements which you want executed in your loop. I.e. open a pair of {} right after the while and close it after the last statement you want inside the loop.
I have minimally edited your code to demonstrate the block:
#include "std_lib_facilities.h"
int main()
{
double i = 0;
double u = 0;
cout << "Enter one numbers:\n";
while (cin >> i)
{ // starting the block of looped statements
if (i > u)
{
cout << "the largest number is: " << i << '\n'
<< "the smallest number is " << u << "\n";
}
else if (i < u) {
cout << "the largest number is " << u << '\n'
<< "the smallest number is " << i << "\n";
}
else if (i == u) {
cout << "The numbers are equal\n";
}
cout << "blabla\n";
} // end the block of looped statements,
// guessing that this is NOT supposed to be inside the loop
keep_window_open();
}

Making an AI program for a project. Can't get it to recognise the user input

So I have to create an AI program than interacts with the user and responds based on the user input. I'm not very experienced, and this has already took hours lmao, I've looked online but I figured I'd actually post my code and try get some help/advice.
Basically the AI helps with maths, I have the program introducing itself and asking what it wants help with but when I enter Addition, Subtraction etc it just responds with numbers when it should respond with "Great, I'll help you with Addition!/(whatever user input)"
Screenshot of first running program: http://prntscr.com/elw7b4
Screenshot after entering what user needs help with: http://prntscr.com/elw7ky
(Obviously it's a bit all over the place at the moment, I did the calculator before anything else hence why it's giving additional results.
The calculator was working before entering the following code: (As you can see http:// prntscr.com /elwavs only two links cos haven't got more than 10 rep)
void Inpsum()
{
cout << "Hello, my name is Eva! I am able to help you with basic Maths! How may I be of Assistance today?" << endl;
float inpsum;
cin >> inpsum;
cout << "Great!, I will help you with " << (inpsum) << endl;
}
but entering the above code broke the calculator.
here is the full code:
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
//user inputs what he needs help with/program output
void Inpsum()
{
cout << "Hello, my name is Eva! I am able to help you with basic Maths! How may I be of Assistance today?" << endl;
cin >> inpsum;
cout << "Great!, I will help you with " << (inpsum) << endl;
}
//addition function
void Add() {
float add1, add2;
cout << "Please enter two values you want added together" << endl;
cin >> add1;
cin >> add2;
cout << "The answer is: " << (add1 + add2) << endl;
}
//subtraction function
void Subt() {
float subt1, subt2;
cout << "Please enter two values you want subtracted" << endl;
cin >> subt1;
cin >> subt2;
cout << "The answer is: " << (subt1 - subt2) << endl;
}
//division function
void Div()
{
float div1, div2;
cout << "Please enter two values you want divided" << endl;
cin >> div1;
cin >> div2;
cout << "The answer is: " << (div1 / div2) << endl;
}
//multiplication function
void Mult() {
float mult1, mult2;
cout << "Please enter two values you want multiplacted" << endl;
cin >> mult1;
cin >> mult2;
cout << "The answer is: " << (mult1 * mult2) << endl;
}
int main()
{
Inpsum(); //user inputs what they want help with
Add();
Subt();
Div();
Mult();
return 0 ;
}
Basically - I've set the calculator up, and it was working. But upon trying to implement input and output between the user and the program I'm going wrong and have broken everything. Instead of the program saying "Great I'll help you with Addition", it says "Great, I'll help you with -134567432"
I'm not asking for anyone to do it for me, rather point me in the right direction so I can actually know what to do in the future.
Notice you define inpsum using float inpsum;, but what you are trying to store is string, or words. They are not compatible. You can learn something more about data types and strings in C++.
It might help to use an enum since you only have a handful of choices. You could do something like this:
enum class OPERATION : char {
Addition = 'A',
Subtraction = 'S',
Division = 'D',
Multiplication = 'M'
};
Then instead you cin to a string and have the following:
std::string input;
std::cin >> input;
switch(static_cast<OPERATION>(input[0])) {
case OPERATION::Addition:
Add();
break;
case OPERATION::Subtraction:
Subt();
break;
case OPERATION::Division:
Div();
break;
case OPERATION::Multiplication:
Mult();
break;
default:
std::cerr << "Invalid input" << std::endl;
exit(1);
}
Defining the enum will allow you to cast values to it which match its values. This allows you to safely do a switch with defined inputs that you expect to see as your program runs.

Expected primary expression before ';' token - new to c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So, I'm tasked with creating a simple calculator, that firstly will take 1 number, than the action you want to perform on it, and than the second number, problem is, I can't get it to work because (at least I think its because of that) the compiler can't take +, -, *, / as a char. what can I do to solve it?
allot of thanks in advance, I've tried to search a solution for a while now and couldn't...
#include <iostream>
using namespace std;
int main()
{
double first;
double second;
char x;
char add = "+" ;
char take = "-" ;
char add2 = "*" ;
char take2 = "/";
cout << "Please enter the first number\n";
cin >> first;
cout << "Please enter the math action\n";
cin >> x;
cout << "Please enter the second number\n";
cin >> second;
; if (x == add)
{
cout << first << x << second << "=" << first+second;
}
if (x == take)
{
cout << first << x << second << "=" << first-second;
}
if (x == add2)
{
cout << first << x << second << "=" << first*second;
}
if (x == take2)
{
cout << first << x << second << "=" << first/second;
}
else
{
cout << "Couldn't reconize the character, please try again";
}
}
There are two things you should correct here.
Use char c = 'x'; instead of char c = "x"; to set a character: double quotes give you a string, and single quotes give you a character.
There's a stray semicolon at the beginning of one of the lines half way through.
You need to remove this ; first from
; if (x == add)
and use single qoute ' while assigning char instead of "

C++ code buggy, needs fixing [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Hey guys I've got this piece of code, posted below. I've added the while loop to make sure that only numeric input is used, but when I use it, it requires me to input the number twice, or press enter and then input the number.
Output would be:
Input number : 1
1
then it would it would print the results. How can I fix this Cheers.
void Dictionary::SearchNumeric()
{
int x;
cout << "Input number : ";
while (!(cin >> x))
{
cout << "Invalid input. Try again: ";
cin.ignore(numeric_limits<streamsize>::max());
}
string searchWord = myWords[x]->word;
cout << "Word searched: " << searchWord << endl;
cout << "Definition: \n" << myWords[x]->definition << endl;
cout << "Type: " << myWords[x]->type << endl;
int wordIndex = 0;
//while (myWords[wordIndex]->word.compare(x) != 0) {
//needs to return scrabble score
wordIndex++;
//break;
//}
}
Get rid of the first cin >> x;, set the string searchWord after the while