在c++中的int中实现前面的0

Implementing a preceding 0 in an int in c++

本文关键字:前面 实现 c++ 中的 int      更新时间:2023-10-16

我试图在用户输入日期后显示它。

因此,如果用户输入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_timestd::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,请将输入作为字符串读取。注意,这就是为什么像电话号码这样的东西在数据库中存储为字符串的原因。这意味着在转换时不会丢失任何东西