在c++中的int中实现前面的0
Implementing a preceding 0 in an int in c++
我试图在用户输入日期后显示它。
因此,如果用户输入2010/10/2作为日期,它应该更改为2010/10/02,在int 中添加前面的0
这是我的相关代码:
请注意,我尝试了setw和setfill,但都不起作用。
file.ignore(1);
file >> year;
file.ignore(1);
file >> mon;
file.ignore(1);
file >> std::right>> setw(2) >> setfill('0') >> day;
您还需要setprecision
,但您需要在打印结果时使用它,而不是在阅读时使用它。
// read the data in:
file >> ignore(1) >> year >> ignore(1) >> mon >> ignore(1) >> day;
// write out the result:
std::cout << std::setfill('0') << std::setprecision(4) << setw(4) << year << "/";
std::cout << std::setprecision(2) << setw(2) << mon << "/";
std::cout << std::setprecision(2) << setw(2) << day << "/";
函数std::get_time
和std::put_time
处理可选的前导0,如果您有现成的参考,可以很容易地指定格式:
std::tm t{};
std::cin >> std::get_time(&t, "%Y/%m/%d"); // %Y, %m, %d take optional leading 0s
if (std::cin.fail()) {
// failed to parse date
} else {
std::cout << std::put_time(&t, "%Y/%m/%d") << 'n'; // %d puts the 0 padding
}
这里有一个实际的例子,代码与链接的引用相比只是略有变化。
每次在C++中读取int或对int执行任何操作时,它都会删除所有前面的"0",因为它们不是必需的。如果您想保留那些0,请将输入作为字符串读取。注意,这就是为什么像电话号码这样的东西在数据库中存储为字符串的原因。这意味着在转换时不会丢失任何东西
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试实现一个函数以删除链表中的结构,同时将它前面的结构分配给它后面的结构