Is there any way to print the integer along with its sign in c++...i.e. by default if the number is negative we would get a - sign printed. In the same way can we get + before the positive numbers.
int x=-1;
cout<<"x="<<x;
gives output x=-1
but,..
int x=+1;
cout<<"x="<<x;
gives output as x=1 but how do i get it printed as x=+1
I know we can take cases by using if-else for x>0 and x<0;..but without using the if-else is there any direct way of printing in c++
Use std::showpos:
int x = 1;
std::cout << "x=" << std::showpos << x;
C++20 std::format option +
According to https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification the following should hold:
#include <format>
// "1,+1,1, 1"
std::cout << std::format("{0:},{0:+},{0:-},{0: }", 1);
// "-1,-1,-1,-1"
std::cout << std::format("{0:},{0:+},{0:-},{0: }", -1);
The existing fmt library implements it for before it gets official support: https://github.com/fmtlib/fmt Install on Ubuntu 22.04:
sudo apt install libfmt-dev
Modify source to replace:
<format> with <fmt/core.h>
std::format to fmt::format
main.cpp
#include <iostream>
#include <fmt/core.h>
int main() {
std::cout << fmt::format("{0:},{0:+},{0:-},{0: }\n", 1);
std::cout << fmt::format("{0:},{0:+},{0:-},{0: }\n", -1);
}
and compile and run with:
g++ -std=c++11 -o main.out main.cpp -lfmt
./main.out
Output:
1,+1,1, 1
-1,-1,-1,-1
More information at: std::string formatting like sprintf
How about:
cout<<"x="<<(x>0)?"+":""<<x;
it's a bit clumsy, but fits the bill
Related
I want to do:
int a = 255;
cout << a;
and have it show FF in the output, how would I do this?
Use:
#include <iostream>
...
std::cout << std::hex << a;
There are many other options to control the exact formatting of the output number, such as leading zeros and upper/lower case.
To manipulate the stream to print in hexadecimal use the hex manipulator:
cout << hex << a;
By default the hexadecimal characters are output in lowercase. To change it to uppercase use the uppercase manipulator:
cout << hex << uppercase << a;
To later change the output back to lowercase, use the nouppercase manipulator:
cout << nouppercase << b;
std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.
If you want to print a single hex number, and then revert back to decimal you can use this:
std::cout << std::hex << num << std::dec << std::endl;
I understand this isn't what OP asked for, but I still think it is worth to point out how to do it with printf. I almost always prefer using it over std::cout (even with no previous C background).
printf("%.2X", a);
'2' defines the precision, 'X' or 'x' defines case.
std::hex gets you the hex formatting, but it is a stateful option, meaning you need to save and restore state or it will impact all future output.
Naively switching back to std::dec is only good if that's where the flags were before, which may not be the case, particularly if you're writing a library.
#include <iostream>
#include <ios>
...
std::ios_base::fmtflags f( cout.flags() ); // save flags state
std::cout << std::hex << a;
cout.flags( f ); // restore flags state
This combines Greg Hewgill's answer and info from another question.
There are different kinds of flags & masks you can use as well. Please refer http://www.cplusplus.com/reference/iostream/ios_base/setf/ for more information.
#include <iostream>
using namespace std;
int main()
{
int num = 255;
cout.setf(ios::hex, ios::basefield);
cout << "Hex: " << num << endl;
cout.unsetf(ios::hex);
cout << "Original format: " << num << endl;
return 0;
}
Use std::uppercase and std::hex to format integer variable a to be displayed in hexadecimal format.
#include <iostream>
int main() {
int a = 255;
// Formatting Integer
std::cout << std::uppercase << std::hex << a << std::endl; // Output: FF
std::cout << std::showbase << std::hex << a << std::endl; // Output: 0XFF
std::cout << std::nouppercase << std::showbase << std::hex << a << std::endl; // Output: 0xff
return 0;
}
C++20 std::format
This is now the cleanest method in my opinion, as it does not pollute std::cout state with std::hex:
main.cpp
#include <format>
#include <string>
int main() {
std::cout << std::format("{:x} {:#x} {}\n", 16, 17, 18);
}
Expected output:
10 0x11 18
Not yet implemented on GCC 10.0.1, Ubuntu 20.04.
But the awesome library that became C++20 and should be the same worked once installed on Ubuntu 22.04 with:
sudo apt install libfmt-dev
or:
git clone https://github.com/fmtlib/fmt
cd fmt
git checkout 061e364b25b5e5ca7cf50dd25282892922375ddc
mkdir build
cmake ..
sudo make install
main2.cpp
#include <fmt/core.h>
#include <iostream>
int main() {
std::cout << fmt::format("{:x} {:#x} {}\n", 16, 17, 18);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main2.out main2.cpp -lfmt
./main2.out
Documented at:
https://en.cppreference.com/w/cpp/utility/format/format
https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification
More info at: std::string formatting like sprintf
Pre-C++20: cleanly print and restore std::cout to previous state
main.cpp
#include <iostream>
#include <string>
int main() {
std::ios oldState(nullptr);
oldState.copyfmt(std::cout);
std::cout << std::hex;
std::cout << 16 << std::endl;
std::cout.copyfmt(oldState);
std::cout << 17 << std::endl;
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
10
17
More details: Restore the state of std::cout after manipulating it
Tested on GCC 10.0.1, Ubuntu 20.04.
How are you!
#include <iostream>
#include <iomanip>
unsigned char arr[] = {4, 85, 250, 206};
for (const auto & elem : arr) {
std::cout << std::setfill('0')
<< std::setw(2)
<< std::uppercase
<< std::hex
<< (0xFF & elem)
<< " ";
}
I have small piece of code for std::for_each_n loop. I tried running it on inbuilt Coliru compiler GCC C++17 using following command :
g++ -std=c++1z -O2 -Wall -pedantic -pthread main.cpp && ./a.out
But compiler give an error that " 'for_each_n' is not a member of 'std' ".
My code is bellow which is copied from cppreference.
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> ns{1, 2, 3, 4, 5};
for (auto n: ns) std::cout << n << ", ";
std::cout << '\n';
std::for_each_n(ns.begin(), 3, [](auto& n){ n *= 2; });
for (auto n: ns) std::cout << n << ", ";
std::cout << '\n';
}
So, Why I'm getting an error?
There is nothing wrong with your code. The issue is that libstdc++ does not support std::for_each_n until GCC 8 and Clang 8. If we look at the header that defines std::for_each_n, we see it does not exist.
However, if you have access to libc++, their header from the official mirror does implement std::for_each_n.
(Update: the current version of the GCC repository now also does include for_each_n)
I have small piece of code for std::for_each_n loop. I tried running it on inbuilt Coliru compiler GCC C++17 using following command :
g++ -std=c++1z -O2 -Wall -pedantic -pthread main.cpp && ./a.out
But compiler give an error that " 'for_each_n' is not a member of 'std' ".
My code is bellow which is copied from cppreference.
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> ns{1, 2, 3, 4, 5};
for (auto n: ns) std::cout << n << ", ";
std::cout << '\n';
std::for_each_n(ns.begin(), 3, [](auto& n){ n *= 2; });
for (auto n: ns) std::cout << n << ", ";
std::cout << '\n';
}
So, Why I'm getting an error?
There is nothing wrong with your code. The issue is that libstdc++ does not support std::for_each_n until GCC 8 and Clang 8. If we look at the header that defines std::for_each_n, we see it does not exist.
However, if you have access to libc++, their header from the official mirror does implement std::for_each_n.
(Update: the current version of the GCC repository now also does include for_each_n)
#include <iostream>
#include <climits>
#include <cinttypes>
using namespace std;
int main()
{
uint16_t i = 0;
cout << USHRT_MAX << '\n' << i - 1 << '\n';
return 0;
}
Output
65535
-1
I expected two equal outputs, but it wasn't. Isn't this a non-standard-compliant behaviour?
*System: Windows7
*Compile Option: g++ -o $(FileNameNoExt) $(FileName) -std=c++11 -Wall -Wextra
When C++ sees the expression
i - 1
it automatically promotes i and 1 to int types, so the result of the expression is an int, hence the output of -1.
To fix this, either cast the overall result of the expression back to uint16_t, or do something like
i--;
to modify i in-place, then print i.
Hope this helps!
i is promoted to an int before the evaluation of i - 1, so the expression i - 1 is itself evaluated as a signed integer (int), try :
cout << USHRT_MAX << '\n' << (uint16_t)(i - 1) << '\n';
Live Demo
When using boost_filesystem, Boost keeps adding quotation marks to the filenames.
foo.cpp:
#include <iostream>
#include <boost/filesystem.hpp>
int main( int argc, char * argv[] )
{
std::cout << argv[0] << std::endl;
boost::filesystem::path p( argv[0] );
std::cout << p << std::endl;
std::cout << p.filename() << std::endl;
return 0;
}
Compiled:
g++ foo.cpp -o foo -lboost_filesystem -lboost_system
Output:
./foo
"./foo"
"foo"
This is somewhat unexpected, and inconvenient in my case. Is this really intentional, or is my somewhat older version of Boost (1.46.1) buggy in this respect? Is there some way I could avoid them being added?
I perused the documentation, but aside from the tutorials not showing those quotation marks in their example output, I was not enlightened.
This is actually a bug filed on the Boost framework on version 1.47.0.
The proposed workaround is:
std::cout << path("/foo/bar.txt").filename().string()
It's intentional because unexpected embedded spaces and confuse related code. The best you can do is probably:
boost::replace_all(yourquotedstring, "\"", "");
EDIT
Although, according to this link, you can try something like:
std::cout << path("/foo/bar.txt").filename().string();