How do I use bitwise shifts with cout? - c++

I'm trying to do something similar to this:
#include <iostream>
int main()
{
std::cout << 1 << 5 << std::endl;
}
I expect 32 (1 shifted left by 5), but I get 15.
I am trying to use a macro like this:
#define BIT_SHIFT(x,y) x << y
...
cout << BIT_SHIFT(1, 5) << std::endl;
and this happens.
Why? How do I fix this?

Just use parentheses:
#include <iostream>
int main()
{
std::cout << (1 << 5) << std::endl;
}
std::cout << 1 << 5 means "push to output stream first integer literal 1, followed by integer 5". However, adding parantheses changes the order of evaluation, and 1 << 5 is evaluated first, resulting in std::cout << 32 << std::endl; expression.

Use parenthesis:
std::cout << (1 << 5) << std::endl;
The reason is that the output ostream& operator<<(ostream&, const T&) overload chains the return values to call the function once more.
If you use parenthesis, the bitshift value is calculated first, and then passed to the overloaded output operator.
I am trying to use this in a macro: ...
Thus the above said your macro definition should look like:
#define BIT_SHIFT(x,y) ((x) << (y))
You may wonder why the extra parenthesis now. This is just safer writing macros. Think about someone tries to use your macro like:
cout << BIT_SHIFT(1, 5*2) << std::endl;

I'm trying to do something similar to this:
#include <iostream>
int main()
{
std::cout << 1 << 5 << std::endl;
}
You're right. You are trying to do something similar to that. However, the problem has nothing to do with the macro (I mean, that's a problem too, but more on that later). The problem is your goal isn't what you mean. You don't mean std::cout << 1 << 5 << std::endl;, you mean std::cout << (1 << 5) << std::endl; The difference is that the first breaks down into something like this:
std::cout << 1;
std::cout << 5;
std::cout << std::endl;
While what you want is something like this:
int i = 1 << 5;
std::cout << i;
std::cout << std::endl;
Or something to that effect.
The answer is simple: either use parenthesis in your cout statement, or put it in your macro (the better option):
// either
cout << (BIT_SHIFT(1, 5)) << std::endl;
// or
#define BIT_SHIFT(x,y) (x << y)
...
cout << BIT_SHIFT(1, 5) << std::endl;
Also, as someone else suggested, you can even go a step further if you like and do this:
#define BIT_SHIFT(x,y) ((x) << (y))
...
cout << BIT_SHIFT(1, 5) << std::endl;
That way, if you do something weird in x or y, your code doesn't break.

Related

How to actually "clear" a vector in C++?

How to clear content in a simple way?
If I use vec_vec.clear(); only, there is still something in the vector that has not been cleaned up.
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<int>> vec_vec(10);
vec_vec[0].push_back(1);
vec_vec[0].push_back(2);
vec_vec[0].push_back(3);
vec_vec[0].push_back(4);
for (auto i : vec_vec[0])
std::cout << i << " ";
std::cout << "." << std::endl;
vec_vec.clear();
for (auto i : vec_vec[0])
std::cout << i << " ";
std::cout << "." << std::endl;
vec_vec[0].clear();
for (auto i : vec_vec[0])
std::cout << i << " ";
std::cout << "." << std::endl;
for (int i=0; i<vec_vec.size(); i++)
vec_vec.erase(vec_vec.begin() + i);
for (auto i : vec_vec[0])
std::cout << i << " ";
std::cout << "." << std::endl;
return 0;
}
1 2 3 4 *
0 0 3 4 *
*
*
vec_vec.clear();
for (auto i : vec_vec[0])
After this clear, vec_vec is empty, so the expression vec_vec[0] has undefined behavior.
Undefined behavior means anything at all might happen, and it's the fault of the program, not the fault of the C++ compiler, library, etc. So it might act like an empty vector, it might crash your program, it might print some values, or it might do what you expect today, then break at the worst possible time later on.
See also this Q&A on Undefined, unspecified, and implementation-defined behavior.

C++ virtual inheritance with abstract class for basic implementation of some math functions

I have troubles with homework. The task is to implement files included in main.cpp so the program will work. main.cpp is the file we get from our teacher - we can't make any changes in it. At the end of it there is written a desired output. (note: there shouldn't be any overloaded operators).
This is what I did so far: https://wandbox.org/permlink/ffzkdaVoYK8Qovic
I can't get it to work properly. I don't know what I am doing wrong:
There must be some error with Differential. Teacher said that we don't need to use clone() method in it - so I didn't - but when I do, in constructor instead of setF, I'm getting segmentation fault. The same happens in function in(), when I'm trying to return the result according to the formula - and I don't get why it happens.
I get -5 instead of 5 (see output below main.cpp). Some math error? I can't spot it.
I have a feeling my class hierarchy is really bad. What should it be instead? (Guessing from the lecture there should be virtual inheritance, multiple inheritance and a solution to diamond problem - but well, that's just my guess.) I'm also getting some warnings when compiling and I didn't fix them because I think I just did the hierarchy wrong and if I fix it the problem will be gone.
In general, what can I fix in my code to make it better?
Here is main.cpp (it's also in the link to my solution):
#include "Fun.h"
#include "Elementary.h"
#include "Compound.h"
#include "Differential.h"
#include <iostream>
int main()
{
std::cout << "=====-===== 2 =====-=====" << std::endl;
Fun * lfun = Linear::create()->a(2.)->b(-1.); // This is ax + b = 2x-1
Fun * sfun = new Sinus;
std::cout << lfun->value(0.1) << " " << lfun->value(0) << std::endl;
std::cout << sfun->value(0.1) << " " << sfun->value(0) << std::endl;
std::cout << "=====-===== 2 =====-=====" << std::endl;
Fun * qbase = Quadratic::create()->a(1)->b(0.)->c(-4.);
Fun * qfun = qbase->clone(); // Cloning
std::cout << qbase->value(0.1) << " " << qbase->value(0) << std::endl;
std::cout << qfun->value(0.1) << " " << qfun->value(0) << std::endl;
delete qbase;
std::cout << qfun->value(0.1) << " " << qfun->value(0) << std::endl;
std::cout << "=====-===== 2 =====-=====" << std::endl;
Differential diff(0.01); // 0.01 is h
std::cout << "value of differential from lfun in 1.0 = " << diff.from(lfun)->in(1) << std::endl;
std::cout << "value of differential from qfun in 2.1 = " << diff.from(qfun)->in(2.1) << std::endl;
std::cout << "value of differential from sfun in 0.12 = " << diff.from(sfun)->in(0.12) << std::endl;
std::cout << "=====-===== 1 =====-=====" << std::endl;
Fun* comp = new Compound(lfun, qfun);
std::cout << "value of compound function " << comp->value(2) << std::endl; // Result from: qfun( lfun( 2 ) )
delete lfun;
delete qfun;
delete sfun;
std::cout << "=====-===== 1 =====-=====" << std::endl;
std::cout << "Compound func still works: " << comp->value(2) << std::endl;
delete comp;
}
/*********************************** OUTPUT ************************************
--------------------------------------------------------------------------------
=====-===== 2 =====-=====
-0.8 -1
0.0998334 0
=====-===== 2 =====-=====
-3.99 -4
-3.99 -4
-3.99 -4
=====-===== 2 =====-=====
value of differential from lfun in 1.0 = 2
value of differential from qfun in 2.1 = 4.2
value of differential from sfun in 0.12 = 0.992792
=====-===== 1 =====-=====
value of compound function 5
=====-===== 1 =====-=====
Compound func still works: 5
--------------------------------------------------------------------------------
*******************************************************************************/

How to print complex numbers in C++

I am playing around with classes in C++. Currently I am working on a class for complex numbers and want to be able to print them in the following format: -2+3i, 1-4i. That means, that I want the real part to have only a sign if it is negative. In contrast the imaginary part should have always a sign whether it is positive or negative.
I tried the following which did not work as expected:
inline void Complex::print() const {
std::cout << x;
std::cout << std::showpos << y << "i" << std::endl;
}
This method prints also for the real part the sign if it is positive. Why does std::showpos affect the first line?
Is there any better way to do that?
showpos is "sticky", and applies to every following number until it's changed back with noshowpos.
You can use showpos with a local stream to avoid messing with std::cout:
inline void Complex::print() const {
std::ostringstream y_stream;
y_stream << showpos << y;
std::cout << x
<< y_stream.str() << 'i'
<< std::endl;
}
When the showpos format flag is set, a plus sign (+) precedes every non-negative numerical value inserted into the stream (including zeros). This flag can be unset with the noshowpos manipulator.
Minor change in your code:
inline void Complex::print() const {
std::cout << std::noshowpos << x;
std::cout << std::showpos << y << "i" << std::endl;
}
That's because the std::showpos flag affects every number inserted into the stream. (http://www.cplusplus.com/reference/ios/showpos/)
Have you tried using if statements?
if (x > 0)
{
std::cout << "+";
}
If you never use std::noshowpos, std::cout will keep the showpos flag, so that next time you call print() it affects x (and any other number you ever print with std::cout in your program).
So either use std::noshowpos directly after printing y:
std::cout << std::showpos << y << std::noshowpos << "i" << std::endl;
or directly before printing x:
std::cout << std::noshowpos << x;

C++ can setw and setfill pad the end of a string?

Is there a way to make setw and setfill pad the end of a string instead of the front?
I have a situation where I'm printing something like this.
CONSTANT TEXT variablesizeName1 .....:number1
CONSTANT TEXT varsizeName2 ..........:number2
I want to add a variable amount of '.' to the end of
"CONSTANT TEXT variablesizeName#" so I can make ":number#" line up on the screen.
Note: I have an array of "variablesizeName#" so I know the widest case.
Or
Should I do it manually by setting setw like this
for( int x= 0; x < ARRAYSIZE; x++)
{
string temp = string("CONSTANT TEXT ")+variabletext[x];
cout << temp;
cout << setw(MAXWIDTH - temp.length) << setfill('.') <<":";
cout << Number<<"\n";
}
I guess this would do the job but it feels kind of clunky.
Ideas?
You can use manipulators std::left, std::right, and std::internal to choose where the fill characters go.
For your specific case, something like this could do:
#include <iostream>
#include <iomanip>
#include <string>
const char* C_TEXT = "Constant text ";
const size_t MAXWIDTH = 10;
void print(const std::string& var_text, int num)
{
std::cout << C_TEXT
// align output to left, fill goes to right
<< std::left << std::setw(MAXWIDTH) << std::setfill('.')
<< var_text << ": " << num << '\n';
}
int main()
{
print("1234567890", 42);
print("12345", 101);
}
Output:
Constant text 1234567890: 42
Constant text 12345.....: 101
EDIT:
As mentioned in the link, std::internal works only with integer, floating point and monetary output. For example with negative integers, it'll insert fill characters between negative sign and left-most digit.
This:
int32_t i = -1;
std::cout << std::internal
<< std::setfill('0')
<< std::setw(11) // max 10 digits + negative sign
<< i << '\n';
i = -123;
std::cout << std::internal
<< std::setfill('0')
<< std::setw(11)
<< i;
will output
-0000000001
-0000000123
Something like:
cout << left << setw(MAXWIDTH) << setfill('.') << temp << ':' << Number << endl;
Produces something like:
derp..........................:234
herpderpborp..................:12345678
#include <iostream>
#include <iomanip>
int main()
{
std::cout
<< std::setiosflags(std::ios::left) // left align this section
<< std::setw(30) // within a max of 30 characters
<< std::setfill('.') // fill with .
<< "Hello World!"
<< "\n";
}
//Output:
Hello World!..................

Formatting C++ console output

I've been trying to format the output to the console for the longest time and nothing is really happening. I've been trying to use as much of iomanip as I can and the ofstream& out functions.
void list::displayByName(ostream& out) const
{
node *current_node = headByName;
// I have these outside the loop so I don't write it every time.
out << "Name\t\t" << "\tLocation" << "\tRating " << "Acre" << endl;
out << "----\t\t" << "\t--------" << "\t------ " << "----" << endl;
while (current_node)
{
out << current_node->item.getName() // Equivalent tabs don't work?
<< current_node->item.getLocation()
<< current_node->item.getAcres()
<< current_node->item.getRating()
<< endl;
current_node = current_node->nextByName;
}
// The equivalent tabs do not work because I am writing names,
// each of different length to the console. That explains why they
// are not all evenly spaced apart.
}
Is their anything that I can use to get it all properly aligned with each other?
The functions that I'm calling are self-explanatory and all of different lengths, so that don't align very well with each other.
I've tried just about everything in iomanip.
Think of it like using Microsoft Excel :)
You think of your stream as fields. So you set the width of the field first then you insert your text in that field. For example:
#include <iostream>
#include <iomanip>
#include <string>
int main()
{
using namespace std;
string firstName = "firstName",
secondName = "SecondName",
n = "Just stupid Text";
size_t fieldWidth = n.size(); // length of longest text
cout << setw(fieldWidth) << left << firstName << endl // left padding
<< setw(fieldWidth) << left << secondName << endl
<< setw(fieldWidth) << left << n << endl;
cout << setw(fieldWidth) << right << firstName << endl // right padding
<< setw(fieldWidth) << right << secondName << endl
<< setw(fieldWidth) << right << n << endl;
}
......
......
The field width means nothing but the width of the text + spaces. You could fill anything other than spaces:
string name = "My first name";
cout << setfill('_') << setw(name.size() + 10) << left << name;
.....
output::
My first name__________
......
I think the best way is to figure out your format then, write a new formatter that does all what you want:
#include <iostream>
#include <iomanip>
#include <string>
std::ostream& field(std::ostream& o)
{
// usually the console is 80-character wide.
// divide the line into four fields.
return o << std::setw(20) << std::right;
}
int main()
{
using namespace std;
string firstName = "firstName",
secondName = "SecondName",
n = "Just stupid Text";
size_t fieldWidth = n.size();
cout << field << firstName << endl
<< field << secondName << endl
<< field << n << endl;
}
If you started thinking about parametrized manipulators, only that accept one int or long parameter are easy to implement, other types are really obscure if you are not familiar with streams in C++.
Boost has a format library that allows you to easily format the ourput like the old C printf() but with type safety of C++.
Remember that the old C printf() allowed you to specify a field width. This space fills the field if the output is undersized (note it does not cope with over-sized fields).
#include <iostream>
#include <iomanip>
#include <boost/format.hpp>
struct X
{ // this structure reverse engineered from
// example provided by 'Mikael Jansson' in order to make this a running example
char* name;
double mean;
int sample_count;
};
int main()
{
X stats[] = {{"Plop",5.6,2}};
// nonsense output, just to exemplify
// stdio version
fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n",
stats, stats->name, stats->mean, stats->sample_count);
// iostream
std::cerr << "at " << (void*)stats << "/" << stats->name
<< ": mean value " << std::fixed << std::setprecision(3) << stats->mean
<< " of " << std::setw(4) << std::setfill(' ') << stats->sample_count
<< " samples\n";
// iostream with boost::format
std::cerr << boost::format("at %p/%s: mean value %.3f of %4d samples\n")
% stats % stats->name % stats->mean % stats->sample_count;
}
Give up on the tabs. You should be able to use io manipulators to set the field width, the fill character, and the format flag (to get left or right justification). Use the same values for the headings as you do for the data, and everything should come out nicely.
Also beware that you've switched Rating and Acres in your example.
You can write a procedure that always print the same number of characters to standard output.
Something like:
string StringPadding(string original, size_t charCount)
{
original.resize(charCount, ' ');
return original;
}
And then use like this in your program:
void list::displayByName(ostream& out) const
{
node *current_node = headByName;
out << StringPadding("Name", 30)
<< StringPadding("Location", 10)
<< StringPadding("Rating", 10)
<< StringPadding("Acre", 10) << endl;
out << StringPadding("----", 30)
<< StringPadding("--------", 10)
<< StringPadding("------", 10)
<< StringPadding("----", 10) << endl;
while ( current_node)
{
out << StringPadding(current_node->item.getName(), 30)
<< StringPadding(current_node->item.getLocation(), 10)
<< StringPadding(current_node->item.getRating(), 10)
<< StringPadding(current_node->item.getAcres(), 10)
<< endl;
current_node = current_node->nextByName;
}
}