读取系统时间,并将月份和日期存在一个string中,如“0213”。 c++
时间: 2024-02-23 19:00:58 浏览: 23
可以使用C++中的时间库`<ctime>`来获取系统时间,并结合字符串流`<sstream>`将月份和日期拼接到一个字符串中。代码如下:
```c++
#include <ctime>
#include <sstream>
#include <iostream>
int main() {
time_t t = time(NULL);
tm* timePtr = localtime(&t);
int month = timePtr->tm_mon + 1;
int day = timePtr->tm_mday;
std::stringstream ss;
if (month < 10) {
ss << "0" << month;
} else {
ss << month;
}
if (day < 10) {
ss << "0" << day;
} else {
ss << day;
}
std::string result = ss.str();
std::cout << result << std::endl;
return 0;
}
```
该程序会输出当前月份和日期拼接成的字符串,如今天是2月13日,则输出为“0213”。
相关问题
c++ 按行读取文件 并将内容存入到另外一个文件中
可以使用与前面类似的方式读取文件,然后使用`std::ofstream`将读取到的内容写入到另一个文件中,以下是示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream input_file("input.txt");
std::ofstream output_file("output.txt");
std::string line;
while (std::getline(input_file, line)) {
output_file << line << std::endl;
}
return 0;
}
```
其中`input.txt`是要读取的文件名,`output.txt`是要写入的文件名,`getline()`函数会读取一行内容并存储到`line`变量中,然后使用`<<`操作符将其写入到输出文件中,每行末尾加上换行符`\n`确保每行之间有回车换行。最后关闭文件流即可。
用户生日存放在一个wstrng中,将它转换成string,再读取系统时间,判断今天是否是用户生日 C++
可以使用C++中的wstring和wstring_convert库来将wstrng转换成string类型,然后再按照之前的方法进行判断。
下面是一个示例代码:
```c++
#include <iostream>
#include <ctime>
#include <string>
#include <locale>
#include <codecvt>
using namespace std;
int main()
{
time_t now = time(0);
tm* local_time = localtime(&now);
wstring user_birthday = L"1990-09-01";
//将wstrng转换成string
wstring_convert<codecvt_utf8<wchar_t>> conv;
string birthday_str = conv.to_bytes(user_birthday);
string birthday_year = birthday_str.substr(0, 4);
string birthday_month = birthday_str.substr(5, 2);
string birthday_day = birthday_str.substr(8, 2);
if (stoi(birthday_year) == local_time->tm_year + 1900 &&
stoi(birthday_month) == local_time->tm_mon + 1 &&
stoi(birthday_day) == local_time->tm_mday)
{
cout << "Happy birthday!" << endl;
}
else
{
cout << "Today is not your birthday." << endl;
}
return 0;
}
```
需要注意的是,需要在代码开头添加`#include <locale>`和`#include <codecvt>`来使用wstring_convert库。