Fix expression; operator precedence [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
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.
Improve this question
I am reading C++ Primer, 5th Edition to learn C++ however I have come across a question that I am kind of stuck at. The question is as follows:
The following expression fails to compute due to operator precedence.
How would you fix it?
string s = "word";
string p1 = s + s[s.size() - 1] == 's' ? "" : "s";
I have tried various solutions but I can't seem to get it. My logic is that the equality operator needs two expressions so I need to create that but my solutions don't work.. Any help is much appreciated!

In general, you don't want to fit your solution in to one line, so lets break this up in to the indivdual parts so we can see why it doesn't work, what we want and how we would do that.
What it is at the moment
string s = "word";
string p1 = s + s[s.size() - 1] == 's' ? "" : "s";
means:
if(s + s[s.size() - 1] == 's')
{
p1 = "";
}
else
{
p1 = "s";
}
What's wrong
It is now clear why this won't work, firstly we are comaring a string (s + s[s.size() -1]) to a character s
Also, looking at the result, I suspect that isn't what you want.
The Fix
Instead we want to append an 's' if the last character is not an s. So in long form:
if(s[s.size() - 1] == 's') // compare the last character
{
p1 = s + ""; // equivalently = s but for clarity in the next step we'll write it like this
}
else
{
p1 = s + "s"; // append the s
}
So now we can condense this back down, adding in brackets to get the desired behaviour
string p1 = s + (s[s.size() - 1] == 's' ? "" : "s");
We append something to s, where the something is determined by the last character of s

I assume you want something like this:
string p1 = s + ((s[s.size() - 1] == 's')? "" : "s");

You want something like:
string s = "word";
string p1 = s + ((s[s.size() - 1] == 's')? "" : "s");

Related

Check an Array String character value without extra variable [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 1 year ago.
Improve this question
suppose I've this code:
string str[] = {"devil", "chandra"};
// check if str[0] has properly devil, character by character or not without extra variable
Now I want to check str[ 0 ]'s all character which is 'd','e','v','i','l' one by one without extra variable.
with extra variable code will be :
string n1 = "devil";
for(int i=0; i<1; i++){
string s1 = str[i]
for(int j=0; j<s1.size(); j++){
if(s1[i] == n[i]){
cout << s1[i] << " ";
}
}
Basically, I want O(n) loop where I can access all indexes string and among them all characters.
Like s[ i ] is "devil" and s[[i]] = 'd' something like this, Know it's not valid, but is there any way to do that??
Even I don't know is it a valid question or not!
I'm not sure why you would need an extra variable. If you need a conditional that checks that the first value in the array of strings is "devil", it shouldn't be anymore complicated than:
if (str[0] == "devil")
{
* Do things *
}
C++ can check a standard string all at once. You don't need to check each individual character if that's what you're thinking.
Keep in mind, this isn't going to account for situations where the string is not exactly the same. For instance, if str[0] has "Devil" instead of "devil", then the conditional will evaluate to false.

terminate called after throwing an instance of 'std::out_of_range' and I don't know how to solve it [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 2 years ago.
Improve this question
I have been working to code, a calculator, that works with recursion.
Input: ! + 1 3
code will do 1+3 and then take the faculity of the sum
output: "24"
I finished writing the basic code( not having filtered out wrong user-input yet),
when I build it shows no warnings, but once I run it I get thrown with the 'std::out_of_range' warning. I tried around and nailed the problem down to one function, but I am unable to identify whats wrong exactly.
//Calculation
string Rechner::berechne(vector <string> t) //Calculator::calculate
{
for (unsigned int i = t.size() - 1; i >= 0; i--) //searches the vector starting from the back
{
if( t.at(i) == "+" || t.at(i) == "*" || t.at(i) == "!") //finds the last operator
{
t.at(i) = differenziere(i, t); //switches out the last operator with
//the result of the operation (differenziere(i, t)
if ( t.at(i) == "!")
{
t.pop_back(); // delets last element of vector and
berechne(t); // searches for the next Operator
}
else
{
t.pop_back(); //delets last two elements
t.pop_back();
berechne(t); //searches for next operator
}
}
}
return t.at(0); //when there is no more operator left, this returns the Result of the whole operation
}
For example
input: 5
the output should be 5, because there is no more operator, but i get the out_of_range warning.
input: + 1 3
has the same output of the warning.
So my best guess is, once the vector consists out of one string, for some reason this falls into the if function, what doesn't make sense to me.
Input is a string, that I convert to a vector. This works all fine, i have tested that.
I am working with code::blocks, c++11 and on a windows laptop.
I hope you can help me.
Also please excuse my english, it's not my native language. I speak fluet normally, but I haven't been around the topic of coding for long, so this is s a little different for me.
i >= 0 will be always true because i is unsigned.
Instead of this
for (unsigned int i = t.size() - 1; i >= 0; i--) //searches the vector starting from the back
{
You can do
for (unsigned int i_loop = t.size(); i_loop > 0; i_loop--) //searches the vector starting from the back
{
unsigned int i = i_loop - 1; // i_loop is positive here thanks to the loop condition

The array index doesnt show the character [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 6 years ago.
Improve this question
I have this code:
#include <stdio.h>
int main(){
char s1[30] = "This is a sentence";
for(int i = 0; i<sizeof(s1);i++){
if(s1[i] = ' '){
printf("+");
}
}
return 0;
}
When I try to loop the array to find all the spaces this happens:
Output: ++++++++++++++++++++++++++++ //30 pluses.
Why doesnt my program outputs 3 pluses?
EDIT: My problem was a simply typo mistake, If you didn't understand what is wrong here take a look at accepted answer.
Change = to == in your if statement.
In your conditional statement, you're assigning space to s[ i ] (operator =). You want to compare them (operator ==).
Try
if (s[ i ] == ' ')
s[ i ] = ' ' is always true because the result of an assignment is the value assigned (space). This value is implicitly converted to a bool (0 = false, anything else = true). Since a space is 32 in ASCII, it will always be true.
References - Assignment Operator, Comparison Operators, ASCII Table
Do this:
if(s1[i] == ' '){
printf("+");
}
= is an assignment operator. To compare two value you need to use == operator. You have used = that that assignment operator always return true so + is being printed out all the time.

How to compare two dates in a program? [closed]

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 8 years ago.
Improve this question
So, there are two dates and I have to check if date1 is further away than date2. What is the best way to do that?
int date1_day = 21, date1_month = 1, date1_year = 1990;
int date2_day = 19, date2_month = 5, date2_year = 1989;
if(???)
{
// date1 is further away
}
I'm struggling with this one for hours.
Try this without using any logical operators:
int date1 = date1_day + date1_month*100 + date1_year*10000;
int date2 = date2_day + date2_month*100 + date2_year*10000;
if(date1 > date2)
printf("date1 is further away than date2\n");
It's not rocket surgery:
if ( date1_year > date2_year ||
(date1_year == date2_year && date1_month > date2_month) ||
(date1_year == date2_year && date1_month == date2_month && date1_day > date2_day))
{
// date1 is further away
}
With a little more thought I'm sure you can come up with a simpler method.
COmpared to the 5 logical operators and 6 compares of Paul, R, here a version with 4 logical operators and 5 compares):
if(date1_year>date2_year ||
(date1_year==date2_year && (date1_month>date2_month
|| (date1_month==date2_month && date1_day>date2_day))))
You can use std::tie from <tuple> to lexicographically compare multiple variables.
if (std::tie(date1_year, date1_month, date1_day) >
std::tie(date2_year, date2_month, date2_day))
{
// date1 is further away
}

Is there a standard C++ tool to parse arithmetic expressions? [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 8 years ago.
Improve this question
What I'm trying to do is described in the comment block immediately inside the function:
bool CalculusWizard::partitionEquation(const std::string & eq, std::string & eq1,
std::string & eq2, CalcWizConsts::eqOps & oper)
{
/* Given an equation eq, partion eq into
eq = eq1 oper eq2
where oper is the operator with the lowest precedence,
e.g. eq = "x*sin(x)+x^2" --> eq1 = "x*sin(x)", oper = ADDITION, eq2 = "x^2".
If there is no operator, e.g. eq = "x", then oper = NONE.
The error checking is done in this function. If there is a syntactical error
in eq, then return false.
*/
bool eqGood = true;
eq1.clear();
eq2.clear();
oper = CalcWizConsts::NONE;
int netParans = 0;
std::string::const_iterator it(eq.begin()), offend(eq.end());
while (it != offend)
{
char thisChar(*it);
char nextChar(((it+1) != offend) ? *(it+1) : '\0');
if (thisChar == '(')
{
if ()
++netParans;
}
else if (thisChar == ')')
{
if (isOp(nextChar))
{
}
--netParans;
}
else if (CalcWizConsts::digMap.count(thisChar) == 1)
{
}
}
if (netParans != 0)
eqGood = false;
return eqGood;
}
You can ignore the gunk that I've started to write. I've just about given up. Time to see whether someone has already done what I'm trying to do.
The operators I have, in order of precedence, are ^, *, /, + and -. The functions that might be in the equation are x, sin(x), cos(x), e^x and log(x) (although I want to be able to add more later). Is there any standard mechanism of doing what I'm trying to do?
What you mostly probably want to do is to break the expression into expression tree - in such form it is a lot easier to process.
To do that, first you need some kind of parser, which will break expression into tokens. Then you can use Reverse Polish Notation conversion algorithm to build an expression tree. Wikipedia page has a lot relevant informations.
In your example, the expression tree would look like the following:
x*sin(x)+x^2
+
/ \
* ^
/ \ / \
x sin x 2
|
x
With this tree you can easily process the whole expression in any way you want.
What you're looking for is a parser that can translate a string into a data structure that represents the expression, taking operator precedence into account. Parsing is a broad topic and you'll need to do some reading, but the Boost Spirit library is a decent way to write parsers in C++, and this SO question also provides some useful background (though it's not specific to C++).