How to print complex numbers in C++ - 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;

Related

Printf and fstream operator << displaying different values. Why?

I'm trying to get the values of x and y coordinates of two eyes. I detect it using opencv XML file, and in the console 2 different x values appear from printf() while the text file I save with operator<< displays 1 value. Why is this so?
printf("X = %o,Y = %o\n", eyes[j].x, eyes[j].y);
ofstream coordinates;
coordinates.open("C:/Users/dougl/Desktop/Coordinates.txt");
coordinates << "X = " << eyes[j].x << "\n" << "Y = " << eyes[j].y;
#include <iostream>
using std::cout;
using std::endl;
using std::oct;
using std::hex;
int main()
{
long int pos_value = 12345678;
cout << "The decimal value 12345678 is printed out as" << endl;
cout << "octal: " << oct << pos_value << endl;
cout << "hexadecimal: " << hex << pos_value << endl << endl;
return 0;
}
Printf showing the Unsigned Octal number for integer using: %o format.
https://www.geeksforgeeks.org/format-specifiers-in-c/amp/
Stream operator<< overload work as per the data type of the value passed.
So, to print octal value you need to formatting (std::oct) :
cout << "octal: " << oct << pos_value << endl;
Reference:http://faculty.cs.niu.edu/~mcmahon/CS241/c241man/node83.html
You are telling printf() to output the integers in octal form, whereas operator<< outputs the integers in decimal form by default.
To make the two outputs match, you need to either:
change %o to %d or %u, depending on whether the x and y values are signed or unsigned, respectively.
use the std::oct I/O manipulator with operator<<.

How do I use bitwise shifts with cout?

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.

C++/CPP Reading an added hex address

I'm still relatively new-ish to CPP but I can't find any source that has my issue. My IDE is MSVC 2017 Preview and my desired outcome is to add two hex addresses together, then read the address' value. I'm not sure why but it's not playing nicely with adding hex numbers. I'll give you my current example:
int number;
ReadProcessMemory(pHandle, (void*)(0x37c90000 + 0xE29FE8), &number, sizeof(number), 0);
std::cout << number << " for " << std::hex << (0x37c90000 + 0xE29FE8) << std::endl;
ReadProcessMemory(pHandle, (void*)(0x38ab9fe8), &number, sizeof(number), 0);
std::cout << number << " for " << std::hex << (0x38ab9fe8) << std::endl;
std::cout << "a = " << (0x37c90000 + 0xE29FE8) << std::endl;
std::cout << "b = " << (0x38ab9fe8) << std::endl;
My predicted outcome of this code would be that both ReadProcessMemory should get the same exact same value, but instead only the second ReadProcessMemory (with the already added hex value) returns properly.
Furthermore, cout-ing A and B report the exact same address. If that's the case, why is ReadProcessMemory throwing a tantrum and reporting a negative number on the first ReadProcessMemory?
Here's my outcome with the code above:
-331287296 for 38ab9fe8
ec40f500 for 38ab9fe8
a = 38ab9fe8
b = 38ab9fe8
Apologies but I truly can't figure out why they're different in any way.
No that seems about right. 0xec40f500 is the unsigned hexadecimal representation of the decimal signed value -331287296. Please learn about two's complement representation of negative numbers.
The problem is, I believe, the std::hex manipulator, which is sticky. If you in the second case use std::dec both numbers will be displayed as decimal:
// Second output
std::cout << std::dec << number << " for " << std::hex << (0x38ab9fe8) << std::endl;
// ^^^^^^^^
// Display *all* following numbers as decimal
Or use std::hex in the first output:
// First output
std::cout << std::hex << number << " for " << (0x37c90000 + 0xE29FE8) << std::endl;
// ^^^^^^^^
// Display *all* following numbers as hexadecimal
Of course, if you intend for number to be unsigned, you need to explicitly say so when defining the variable. Perhaps it would be easier for you to see the connection between 0xec40f500 and the unsigned decimal value 3963680000?

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;
}
}