0

I have noticed strange behaviour when printing output to a stream. My code loops through a large dataset and, amongst other things, reads a timestamp from each item. The timestamp from the first item is stored so an elapsed time can be calculated.

CurTime = ev[i].MidasTimeStamp;
RunTimeElapsed = difftime(CurTime,StartTime);
cout << "StartTime: " << ctime(&StartTime) << "CurTime: " << ctime(&CurTime) << "Elapsed: " << RunTimeElapsed << " s" << endl;  

The output printed to screen shows the same time printed twice e.g:

StartTime: Mon Sep 23 14:44:57 2013
CurTime: Mon Sep 23 14:44:57 2013
Elapsed: 360 s

But if split the print line into two:

cout << "StartTime: " << ctime(&StartTime); 
cout << "CurTime: " << ctime(&CurTime) << "Elapsed: " << RunTimeElapsed << " s" << endl; 

I get the expected output:

StartTime: Mon Sep 23 14:44:57 2013
CurTime: Mon Sep 23 14:50:57 2013
Elapsed: 360 s

The only change between the two outputs was to the cout line(s). This is easy enough to work around but I'd like to understand what's happening.

4

1 回答 1

3

从文档中ctime

返回的值指向一个内部数组,其有效性或值可能会被任何后续调用 asctime 或 ctime 更改。

未指定表达式中子表达式的求值顺序。特别是,编译器可以先调用ctime两次,然后operator<<根据需要调用。这就是你的情况似乎发生的事情。

于 2013-10-17T21:54:42.753 回答