Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 views
in Technique[技术] by (71.8m points)

c++ - How Can I Tell if My struct tm Has Been Left in an Invalid State?

This is a question about invalid input, not invalid formatting. For example given the following code:

tm bar;

foo >> get_time(&bar, "%Y-%m-%d");

cout >> bar.tm_year >> bar.tm_mon >> bar.tm_mday >> endl;

This is fine if I define: stringstream foo("2001-02-28 non-leap year"); And has a clear error if I have invalid format such as: stringstream foo("bad format 2001-02-28 non-leap year");

But I don't know how to detect if my input was invalid for example:

stringstream foo("2001-02-30 non-leap year");

In this case bar can be read as though nothing was wrong. Is there something I can listen for which will alert me that the input was invalid?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since mktime tries to interpret also out-of-range values (i.e. for 2001-02-30 will be interpreted as 2001-03-01), you can do an mktime followed by a localtime, if you get different values back it means that the original ones were not valid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...