Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with setfill in a member function

Tags:

c++

I am trying to create a program over multiple files that reads out the time, but I am having trouble displaying the time in the desired format. More specifically, setfill appears to be causing me problems.

Here is the beginning of a very long error messages I recieve when compiling:

error: no match for ‘operator<<’ in ‘std::operator<< [with _CharT = char, 
_Traits = std::char_traits<char>](((std::basic_ostream<char, 
std::char_traits<char> >&)(& std::cout)), std::setw(2)) << std::setfill 
[with _CharT = const char*](((const char*)"0"))’

Now, this message only appears when I have setfill in my member function. If I remove setfill there is no issues with output except the format is wrong.

The member function is:

Void Time::print()
{
    cout << setw (2) << setfill ("0") << hours << ":";
    cout << setw (2) << setfill ("0") << minutes << ":";
    cout << setw (2) << setfill ("0") << seconds << endl;
}

To be clear, I have included iomanip and setw has no problem working on its own.

Thanks.

like image 582
Miles Avatar asked Mar 31 '11 07:03

Miles


People also ask

What is setfill function in C++?

C++ iomanip Library - setfill Function. Description. The C++ function std::setfill behaves as if member fill were called with c as argument on the stream on which it is inserted as a manipulator (it can be inserted on output streams). It is used to sets c as the stream's fill character.

What is the use of setfill in streams?

The stream object on which it is inserted or extracted is modified and concurrent access to the same stream object may introduce data races. Object is in a valid state, if any exception is thrown. Let's see the simple example to demonstrate the use of setfill:

What does out << setfill(C) do?

When used in an expression out << setfill(c) sets the fill character of the stream out to c . Returns an object of unspecified type such that if out is the name of an output stream of type std::basic_ostream<CharT, Traits>, then the expression out << setfill(n) behaves as if the following code was executed:

What is the declaration for STD::setfill function?

Following is the declaration for std::setfill function. c − The new fill character for the stream. char_type is the type of characters used by the stream (i.e., its first class template parameter, charT).


2 Answers

In addition, if you are using a wstringstream, setfill wants a wchar.

Compare

std::stringstream ss;
ss << std::setw(2) << std::setfill('0') << hours << ":";

with

std::wstringstream ss;
ss << std::setw(2) << std::setfill(L'0') << hours << ":";
like image 157
DoubleChain Avatar answered Oct 27 '22 13:10

DoubleChain


setfill takes a char, it should be '0' instead of "0"

like image 22
jonsca Avatar answered Oct 27 '22 12:10

jonsca