成员函数中setfill的问题

5

我正在尝试创建一个跨多个文件的程序,读取时间,但我在显示所需格式的时间方面遇到了问题。更具体地说,setfill似乎给我带来了麻烦。

以下是编译时我收到的非常长的错误消息的开头:

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"))’

现在,只有当我在成员函数中使用setfill时,才会出现此消息。如果我删除setfill,则输出没有问题,只是格式不正确。
该成员函数为:
Void Time::print()
{
    cout << setw (2) << setfill ("0") << hours << ":";
    cout << setw (2) << setfill ("0") << minutes << ":";
    cout << setw (2) << setfill ("0") << seconds << endl;
}

要明确的是,我已经包含了和,它们本身没有任何问题。
谢谢。
4个回答

9
此外,如果您正在使用wstringstream,则setfill需要一个宽字符(wchar)。
比较
std::stringstream ss;
ss << std::setw(2) << std::setfill('0') << hours << ":";

使用

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

6

setfill函数需要一个字符作为参数,应该使用'0'代替"0"


2

你应该:

cout << setw (2) << setfill ('0') << hours << ":";
cout << setw (2) << setfill ('0') << minutes << ":";
cout << setw (2) << setfill ('0') << seconds << endl;

1

setfill函数需要一个char类型的参数,而不是char*类型的参数,所以应该使用'0'


1
请注意,"0"是一个const char *而不是char * - Björn Pollex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接