I have run into a strange to me problem. For some reason multiple || statements, even divided by commas and parenthesis will not work. The last thing I expected to work is the & statement, which requires for both conditions to be met, but in my case it works for one condition as if it was an OR statement.
Someone please explain to me why is this happening. I am very confused.
WORKS:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
string quest;
quest = "Where is my dog?";
string::iterator m;
vector<string>question;
string t;
for(m = quest.begin(); m != quest.end(); m++)
{
if(*m != ' ' & *m != ',' & *m != '?' & *m != '.') //works with & and &&
{
t.push_back(*m);
}
else
{
cout << t << endl;
question.push_back(t);
t.clear();
}
}
}
Does not work:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
string quest;
quest = "Where is my dog?";
string::iterator m;
vector<string>question;
string t;
for(m = quest.begin(); m != quest.end(); m++)
{
if(*m != ' ' || *m != ',' || *m != '?' || *m != '.') // DOES NOT WORK
{
t.push_back(*m);
}
else
{
cout << t << endl;
question.push_back(t);
t.clear();
}
}
}
Or looks at the first if it doesn’t match it goes onto the next one and checks it else it executes the code. So if m is ‘ ‘ it’ll fail the first test, but the second test will pass as ‘ ‘ is not ‘,’.
I expect what you actually want is something along the lines of: