Printing % character attached to floating number - c++

So Let's say I am overloading OS operator and I want to have some sort of table of values divided into columns looking like this:
┌───────────────┬──────────────────────┬─────────────┬──────────────┐
│ X │ Y. │ Z. │ value │
├───────────────┼──────────────────────┼─────────────┼──────────────┤
and below I am printing those Values using stream:
<< std::setw(13) << std::noshowpoint << value << "%" << "|" << endl;
how can I do this so the output of let's say value equal to 5 will be printed as 5%
I tried to use to_string method but results were overriding noshowpoint operator.

First create the string for the value and percent sign.
Then use that string with the formatting.
You can do the first part using a string output stream. And you can combine it into a single statement:
std::cout << std::setw(13)
<< (std::ostringstream{ } << std::noshowpoint << value << '%').str()
<< "|\n";

Related

Strange incrementing of iterators when passing them as an argument

I immediately apologize for my terrible English :D
For my project, I need to analyze the obj file. I line-by-line read the file and select data from a specific string using regular expressions.
regex regCoord("-?\\d+\.?\\d*");
sregex_iterator a(line.begin(), line.end(), regCoord);
I know for sure that 3 matches have been found and I want to use them right away. For example, output to the console or save to a structure
cout << line << endl;
cout << a++->str() << " " << a++->str() << " " << a->str() << endl;
But in this case, incrementing occurs in the reverse order, from left to right! And on the output I get not (1st element, 2nd element, 3rd element), but (2nd element, 1st element, 1st element). A similar problem occurs if I pass all three elements to the structure constructor.
Output:
v 0.151164 0.014830 -0.051720
0.014830 0.151164 0.151164
But if I loop through the elements or write output in three lines, the result will look normal. Likewise, if I fill a structure without using a constructor, and write to each of its fields separately.
cout << a++->str() << " ";
cout << a++->str() << " ";
cout << a->str() << endl;
Output:
v 0.151164 0.014830 -0.051720
0.151164 0.014830 -0.051720
Why can there be such a strange inverted argument handling? I'm using Visual Studio 2017

Why fstream::tellg() return value is enlarged by the number of newlines in the input text file, when file is formated for Windows (\r\n)?

Program openes input file and prints current reading/writing position several times.
If file is formated with '\n' for newline, values are as expected: 0, 1, 2, 3.
On the other side, if the newline is '\r\n' it appears that after some reading, current position returned by all tellg() calls are offsetted by the number of newlines in the file - output is: 0, 5, 6, 7.
All returned values are increased by 4, which is a number of newlines in example input file.
#include <fstream>
#include <iostream>
#include <iomanip>
using std::cout;
using std::setw;
using std::endl;
int main()
{
std::fstream ioff("su9.txt");
if(!ioff) return -1;
int c = 0;
cout << setw(30) << std::left << " Before any operation " << ioff.tellg() << endl;
c = ioff.get();
cout << setw(30) << std::left << " After first 'get' " << ioff.tellg() << " Character read: " << (char)c << endl;
c = ioff.get();
cout << setw(30) << std::left << " After second 'get' " << ioff.tellg() << " Character read: " << (char)c << endl;
c = ioff.get();
cout << setw(30) << std::left << " Third 'get' " << ioff.tellg() << "\t\tCharacter read: " << (char)c << endl;
return 0;
}
Input file is 5 lines long (has 4 newlines), with a content:
-------------------------------------------
abcd
efgh
ijkl
--------------------------------------------
output (\n):
Before any operation 0
After first 'get' 1 Character read: a
After second 'get' 2 Character read: b
Third 'get' 3 Character read: c
output (\r\n):
Before any operation 0
After first 'get' 5 Character read: a
After second 'get' 6 Character read: b
Third 'get' 7 Character read: c
Notice that character values are read corectly.
The first, and most obvious question, is why do you expect any
particular values when teh results of tellg are converted to
an integral type. The only defined use of the results of
tellg is as a later argument to seekg; they have no defined
numerical significance what so ever.
Having said that: in Unix and Windows implementations, they will
practically always correspond to the byte offset of the
physical position in the file. Which means that they will have
some signification if the file is opened in binary mode; under
Windows, for example, text mode (the default) maps the two
character sequence 0x0D, 0x0A in the file to the single
character '\n', and treats the single character 0x1A as if it
had encountered end of file. (Binary and text mode are
indentical under Unix, so things often seem to work there even
when they aren't guaranteed.)
I might add that I cannot reproduce your results with MSC++.
Not that that means anything; as I said, the only requirements
for tellg is that the returned value can be used in a seekg to
return to the same place. (Another issue might be how you
created the files. Might one of them start with a UTF-8
encoding of a BOM, for example, and the other not?)

Pushing all the numbers on a line in a file into a stringstream

For my map creation algorithm, the user inputs numbers such as this in a data file:
0, 3, 0, 0
14, 2, 26, 5
The numbers represent the id of a certain texture of a tile in order to generate cell/world data. I've already made the part that takes away the commas to make it look like this:
0 3 0 0
14 2 26 5
The problem I'm having is that I want to push the certain numbers into a stringstream so they can be parsed and given the correct texture. The certain numbers will be 1 space away from each other so it's easy to push it into the stringstream, but how would I jump from each number to another in order to push it into the stringstream in the same order?
Thanks!
Maybe something like this:
std::string snumbers = ...; // your input string with no commas
std::stringstream sstream(snumbers);
std::vector<std::string> items;
std::string item;
while(sstream >> item) items.push_back(item);
const size_t N = items.size() / 2; // this is the number of pairs you have
std::cout << "pair 0: " << items[0] << ", " << items[N] << std::endl;
std::cout << "pair 1: " << items[1] << ", " << items[1+N] << std::endl;
...

How to use setw with objects

I'm trying to format output using the NTL library (a number theory library). One of the objects is the GF2X object, which is a polynomial represented as a string of coefficients. A quick example:
GF2X a = GF2X(5,1);
a++;
cout<<a;
will yield [1 0 0 0 0 1] which is the same as x^5 + 1. My question is about formatting this output using setw. I want to be able to output various length GF2X objects, prepended by a number, and appended with a string. I'd like my output to look like the following:
1: [x x x x x x x x] string here
15: [x x x] string here
I would also settle for the right ] to be aligned, which is what I should probably expect if I'm using setw. However, when i use the code (variable names ommitted for simplicity):
cout << setw(3)<< int <<": "<< setw(35) << GF2X << setw(15) << string << endl;
I get output more like this (some white space removed for compactness)
1: [x x x x x x x x] string here
15: [x x x] string here
In other words, the setw function seems to be treating the entire output of <<GF2X as a single character, and doesn't seem to actually account for the size of the output string. As you can see from the output I've shown you, the left side of the GF2X output is aligned, but the right side isn't, whereas typically, setw seems to align the right side of outputs.
You can do it with a modification to the output operator. I imagine it's written something like this (I don't know anything about this GF2X class, so this is partially psuedo-code:
std::ostream & operator<<(std::ostream & os, const GF2X & x)
{
os << '[';
for (int i=0; i<x.num_elements; ++i)
os << x.get_element(i) << ' ';
return os << ']';
}
The problem is that setw will only operate on that first '[', it doesn't operate on the whole object (it doesn't know what the whole object is). You can fix the operator by writing the whole thing to a string (using stringstream or some other means), and then outputting the string. If modifying the operator is not an option for you, then you will need to use a separate helper function to first convert the object to a string (using a stringstream), then output that string to the stream.
Actually, boost::lexical_cast would come in really handy for you here, since it will do that last for you:
cout << setw(35) << boost::lexical_cast<std::string>(GF2X);
You can use a temporary ostringstream object to hold the output, and then use setw on the string provided (variable names omitted).
ostringstream oss;
oss << GF2X;
cout << setw(3) << x << ": "<< setw(35) << oss.str() << setw(15) << string <<endl;
This formats the entire ostream object, rather than just the first character, and gives the proper output.

How can I change the precision of printing with the stl?

I want to print numbers to a file using the stl with the number of decimal places, rather than overall precision.
So, if I do this:
int precision = 16;
std::vector<double> thePoint(3);
thePoint[0] = 86.3671436;
thePoint[1] = -334.8866574;
thePoint[2] = 24.2814;
ofstream file1(tempFileName, ios::trunc);
file1 << std::setprecision(precision)
<< thePoint[0] << "\\"
<< thePoint[1] << "\\"
<< thePoint[2] << "\\";
I'll get numbers like this:
86.36714359999999\-334.8866574\24.28140258789063
What I want is this:
86.37\-334.89\24.28
In other words, truncating at two decimal points. If I set precision to be 4, then I'll get
86.37\-334.9\24.28
ie, the second number is improperly truncated.
I do not want to have to manipulate each number explicitly to get the truncation, especially because I seem to be getting the occasional 9 repeating or 0000000001 or something like that that's left behind.
I'm sure there's something obvious, like using the printf(%.2f) or something like that, but I'm unsure how to mix that with the stl << and ofstream.
Use std::fixed , this should work for you.
file1 << std::fixed << std::setprecision(precision)
<< thePoint[0] << "\\"
<< thePoint[1] << "\\"
<< thePoint[2] << "\\";
Try
file1 << std::setiosflags(ios::fixed) << std::setprecision(precision)
which sets fixed-point format instead of floating-point.
(By the way, this is not STL. It's iostream.)
…Oh! I think Kumar bettered me with std::fixed.