我从服务器接收string such as "2011-08-12,02:06:30"
,指定数据和时间。
但是如何将其转换为int并存储如
int year = 2011, month =08, day = 14, h = 02, min = 06, sec=30
。
答案 0 :(得分:4)
sscanf功能可以帮到你。
int year, month, day, h, min, sec;
char * data = "2011-08-12,02:06:30";
sscanf(data, "%d-%d-%d,%d:%d:%d", &year, &month, &day, &h, &min, &sec);
答案 1 :(得分:4)
您可以在C ++中使用stringstream
类。
#include <iostream>
// for use of class stringstream
#include <sstream>
using namespace std;
int main()
{
string str = "2011-08-12,02:06:30";
stringstream ss(str);
int year, month, day, h, min, sec;
ss >> year;
ss.ignore(str.length(), '-');
ss >> month;
ss.ignore(str.length(), '-');
ss >> day;
ss.ignore(str.length(), ',');
ss >> h;
ss.ignore(str.length(), ':');
ss >> min;
ss.ignore(str.length(), ':');
ss >> sec;
// prints 2011 8 12 2 6 30
cout << year << " " << month << " " << day << " " << h << " " << min << " " << sec << " ";
}
答案 2 :(得分:3)
您可以编写自己的字符串解析器来将字符串解析为必要的组件(类似于有限状态机设计在这里会很好),或者......
不要重新发明轮子,并使用类似Boost Date & Time库的东西。
答案 3 :(得分:1)
您还可以在任何符合POSIX标准的平台上使用strptime()
功能,并将数据保存到struct tm
结构中。一旦采用struct tm
的格式,您还将有一些额外的自由来利用其他POSIX函数struct tm
定义的时间格式。
例如,为了解析从服务器发回的字符串,您可以执行以下操作:
char* buffer = "2011-08-12,02:06:30";
struct tm time_format;
strptime(buffer, "%Y-%d-%m,%H:%M:%S", &time_format);