Reading backslash characters literally in c++ - c++

In my c++ code, I am trying to read \ and / characters literally, but \ is read as being same as /.
My code is this:
int x, y;
char orient;
cin >> N >> goalA >> goalB;
for (int i = 0; i < N; i++)
{
cin >> x >> y >> orient;
xVal [i] = x;
yVal [i] = y;
if (orient = '/')
{
orientVal [i] = 1;
}
else
{
orientVal [i] = 2;
}
cout << orientVal[i];
}
but even when orient = '\', I get orientVal [i] = 1 instead of 2. How can I fix this? Thanks.

An assignment is done with = and an equality with ==
So the statement
if (orient = '/')
should be
if (orient == '/')
The first statement always evaluates to true irrespective of what orient contains. Because in C/C++ a non zero value is True. Your assignment makes the statement to simply as
if ('/')
which is nothing but
if (true)

Because if (orient = '/') is an assignment that always evaluates to true as a boolean (non-zero).
You want if (orient == '/').

Line
if(orient = '/'
Should be
if ('/' == orient) ...

Related

A loop never starts

I'm writing a simple function that is supposed to read an input from a user as a string. Check if the strings solely consist of digits then converts it to and int and returns it. The problem is the loop never used regardless of the input. I'm struggling to find the root of the problem.
int correctInt()
{
string temp;
int input;
bool m;
do
{
m = false;
getline(cin, temp);
int length=temp.length();
for (int a = 0; a < length; a++)
{
if (temp[a] < '0' && temp[a]>'9')
{
cout << "ID should consist of numbers. Try again: ";
m = true;
break;
}
}
if (!m)
{
return input = atoi(temp.c_str());
}
} while (1);
}
Thank you in advance
You should use OR instead of AND:
temp[a] < '0' || temp[a]>'9'
Try to change && (and) condition to || (or) condition
if (temp[a] < '0' || temp[a]>'9')

Confused over while(cin >> x && x != 0) (when int x = 0) versus while(x != 0 && cin >> x ) (when int x = 1)

In my university's lecture today, we were given this:
input: 1, 2, 3, 0, 4
and two different codes
(1)
int x = 0;
int sum = 0;
int count = 0;
while (cin >> x && x != 0) {
sum += x;
count++;
}
cout << static_cast<double>(sum) / count;
(2)
int x = 1;
int sum = 0;
int count = 0;
while (x != 0 && cin >> x ) {
sum += x;
count++;
}
cout << static_cast<double>(sum) / count;
I understand the first code ends with an output of 2, but apparently the second output ends with an output of 1.5 (6/4). My confusion is over why the count is 4 if the loop becomes false after inputting zero - is it the location of the cin in the condition, the initialized x? I am confused. Thank you!
What happens when you reach the zero?
while (cin >> x && x != 0)
You read in the zero and discover that x is 0. You will stop iteration.
while (x != 0 && cin >> x)
Now x is set to zero, but you have checked previous value of x, which hasn't yet been zero then. So you will enter the loop again:
sum += 0; // the current value of x
count++; // one summand more
and only discover that x got zero when checking the loop condition in the subsequent loop run.
In other words, in second variant, you count the zero as additional summand.
In the second case, the loop is entered with x == 0. It stops after adding 0 to sum and incrementing count.
In the first loop the value 0 is not countered. While in the second loop the value 0 is countered in the variable count.
while (x != 0 && cin >> x ) { // <== 0 is read
sum += x;
count++; // <-- and count is increased
}
In fact in the first loop the condition x != 0 is a pre-condition while in the second loop the condition is a post-condition.
The second loop can be equivalently rewritten (provided that the input was successfull) like
do
{
cin >> x;
sum += x;
count++;
} while ( x != 0 );

how to calculate polynomial (x^2^2^2^2+x^2^2^2)

I want to calculate (x^2^2^2^2+x^2^2^2) result should be [x^256+x^16]..but i am unable to do this completely..i also have written a code which is working for first half(before '+') but in other half it fails to do it...
#include<iostream>
#include<string>
#include <algorithm>
#include<sstream>
using namespace std;
int main()
{
string a;
cin >> a;
string s1 = "^";
string::size_type foud;
foud = a.find(s1);
int i = foud;
int flag = 0;
i++;
while (foud != std::string::npos)
{
flag = 0;
cout << i <<"I"<< endl;
while (flag != 1 && i < a.length())
{
if (a[i] == '(' || a[i] == '+' || a[i] == '-' || a[i] == ')')
{
flag++;
cout << "terminator" << endl;
}
else if (a[i] == '^')
{
/*int j = (int)(a[i - 1]);
j = j - 48;
int k = (int)(a[i + 1]);
k = k - 48;
i = k + 1;
int power =0;
power = pow(j, k);
;*/
int j = i;
int k = i;
k--;
j++;
string bcknumber;
while (a[k] != '^' && a[k] != '(' && a[k] != '+' && a[k] != '-' && a[k] != ')')
{
bcknumber = bcknumber + a[k];
k--;
}
cout << bcknumber << endl;
reverse(bcknumber.begin(), bcknumber.end());
cout << bcknumber << endl;
int BK;
BK = stoi(bcknumber);
int FD;
string frdnum;
while (a[j] != '^'&&a[j] != '\0' && a[j] != '(' && a[j] != '+' && a[j] != '-' && a[j] != ')')
{
frdnum = frdnum + a[j];
j++;
}
FD = stoi(frdnum);
int resil = pow(BK, FD);
frdnum.clear();
stringstream s;
string res;
s << resil;
res = s.str();
if (i == 15)
{
a.replace(14, 15, res);
}
else
{
a.replace(i - bcknumber.length(), i + frdnum.length(), res);
}
i--;
bcknumber.clear();
}
else
i++;
}
foud = a.find("^", foud + 1);
i = foud;
i++;
}
cout << a << endl;
system("pause");
}
This is not a trivial problem. You want to build an infix calculator (a + b). A prefix calculator (+ a b) or a postfix calculator (a b +) are simpler, since there are no ambiguities at all. An infix calculator can have a lot of them, depending on the degree of freedom you want the user to have.
In the problem you're exposing, one is tempted to say: well, if there is an operator next to the second operand, then I have to accumulate the last result and operate with that and the next operation. However, there are problems like precedence which will not be deal with with that approach.
I would start creating a prefix calculator. It is a lot easier:
calculate():
opr = match operator
op1 = match operand
if op1 is operator:
back
op1 = calculate
op2 = match operand
if op2 is operator:
back
op2 = calculate
return calc(opr, op1, op2)
Once you have mastered that, then there is the possibility to start with an infix calculator.
One thing to do in the last algorithm would be to change it to avoid recursion, for example.
This is a good exercise, enjoy it. Hope this helps.
This smells like homework/assignment so I will not provide code...
As I see it you want just string parser to string replacing the power part. I am assuming You still do not understand the power math or are wrongly writing/interpreting representation of the string. For example:
x^2^2^2^2 =
(((x^2)^2)^2)^2 =
(((x.x)^2)^2)^2 =
((x.x).(x.x))^2)^2 =
((x.x.x.x))^2)^2 =
((x.x.x.x).(x.x.x.x))^2 =
(x.x.x.x.x.x.x.x)^2 =
(x.x.x.x.x.x.x.x).(x.x.x.x.x.x.x.x) =
(x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x) =
x^16
And not yours x^256. You can not add parenteses where you want they must be placed according to order of math operations otherwise the resulting equation will not match the input string !!!. In case you got defined different parse rules for your parser then in standard math then you need to define them in the Question.
Now how to approach this:
read string
I would start with constant hard-coded string instead of typing it all the time while programing/debugin over and over (as many students do ... I saw few times people typing 5x5 matrix on each build :) ... which is insane)
When the program works only then use the cin reading... as you already do
detect which part of the string is power exponent
exponent=1
Search the string for first ^ and remember the start position i0 if not found goto #4.
Now depending on what follows:
If number multiply exponent by it.
If ^ skip it and goto to #2
if neither stop
Of coarse if you should support parentes then it will be much much more complicated and you need to decode the whole thing which is not trivial which you should also mention in the Question.
replace original exponent string with computed string (if computable)
so the computed string will be "^"<<exponent or "^"+exponent depends on what kind of string arithmetics you using ....
output string
with cout or whatever as you already do

Extraction operator causing my program to exit?

I'm a usual lurker but this is my first post! I understand you guys like detail so I will do my best. I will appreciate whatever input anyone has.
I am working on an overloading the extraction operator for an object with a dynamic array of digits. The console input will have leading white space, then an int, then anything after. I need to ignore white space, extract the int, and then leave the rest alone. Easy right?
Here is an example of code I found online:
istream & operator >> (istream &m, MyInt & p)
{
int x = 0;
p.currentLength = 0;
while ((m.peek() == '\n') || (m.peek() == '\0') ||
(m.peek() == '\t') || (m.peek() == ' '))
{
m.get();
}
while ((m.peek() >= '0') && (m.peek() <= '9'))
{
if (p.currentLength >= p.maxSize)
{
p.grow();
}
m >> p.theNumber[x];
x++;
p.currentLength++;
}
m.get();
// reverse the order (i.e. - 123 to 321)
char * temp = new char[p.maxSize];
for (int y = 0; y < p.currentLength; y++)
{
temp[y] = p.theNumber[p.currentLength - 1 - y];
}
delete [] p.theNumber;
p.theNumber = temp;
return m;
}
Now, I understand this method may work, however to me, that seems like an extremmeelly inefficient method. For a trillion digit number, Grow() would reallocate the array a trillion times! Perhaps this is not as bad as I think it is?
My current method has been using seekg() and peek() and get(). Like so:
istream& operator >> (istream& is, MyInt& z)
{
int i = 0, j = 0;
// check if next char is white
while (is.peek() == 38)
{
j++;
is.seekg(j); // skip if white
}
while (isdigit(is.peek()))
{
i++;
is.seekg(j + i);
if (!is.peek())
{
is.clear();
break;
}
}
is.seekg(j);
z.length = i;
z.digits = new int[i + 1];
for (i = 0; i < z.length; i++)
{
z.digits[i] = C2I(is.get());
}
return is;
}
Also, here is my main:
int main()
{
MyInt B;
cout << "\n\nChange B to what num? ---> ";
cin >> B;
cout << "B is now: " << B;
char c;
cout << "\n\n\n\n\nEnter char to exit : ";
cin >> c;
return 0;
}
For the life of me I can not find what is causing my program to exit. The last output seems to say, 'B is now: -1'
I believe the this means the << B failed. I have B initialized to 0 currently, and the rest of my code has presented no other issues. It's private member data only include the pointer and a length (num of digits). Also C2I() is a function that converts '0' through '9' to 0 through 9.
A big issue for me is I am fairly new to parsing, so I don't have very eloquent ways to test this, or other ideas.
Again I appreciate everything you guys do. I have already learned a great deal from browsing here!

Using ifstream as fscanf

Assume that I have an input as follows:
N (X_1,Y_1) (X_2,Y_2) .... (X_N, Y_N)
where N, X_i and Y_i are integers.
An example:
2 (55,1) (521,7)
To read this, I can do something like this(assume all variables are defined, etc.):
fscanf(fin,"%d ",&N);
for (int i = 0; i < N; i++)
fscanf(fin,"(%d,%d) ", &X[i], &Y[i]);
The question is, how can I do this easily using ifstream. I can get string's, and then I can get rid of nondigits and using stringstream I can get two numbers but this seems a bit cumbersome. Is there an easier, more elegant way?
Thanks
int n, x, y;
char c;
if (is >> n)
for (int i = 0; i < n; ++i)
if (is >> c && c == '(' &&
is >> x &&
is >> c && c == ',' &&
is >> y &&
is >> c && c == ')')
{
X[i] = x;
Y[i] = y;
}
else
throw std::runtime_error("invalid inputs");
You can simplify the all-important inner if condition above to...
is >> chlit('(') >> x >> chlit(',') >> y >> chlit(')')
...with a simple support type for consuming a specific character:
struct chlit
{
chlit(char c) : c_(c) { }
char c_;
};
inline std::istream& operator>>(std::istream& is, chlit x)
{
char c;
if (is >> c && c != x.c_)
is.setstate(std::iostream::failbit);
return is;
}
See a complete program illustrating this on ideone here.
An old post of mine did something similar for consuming specific strings. (The above chlit could be a template, but chlit<','>() is ugly to read and write - I'd rather trust the compiler).
cin >> N;
for (int i = 0; i < N; i++)
{
cin.ignore(100,'(');
cin >> X[i];
cin.ignore(100,',');
cin >> Y[i];
cin.ignore(100,')');
}
It can handle whitespaces also, as it can read input like:
2 ( 1 , 3 ) ( 5 , 6 )
Demonstration at ideone: http://www.ideone.com/hO0xG