分类: LINUX
2009-08-13 15:09:27
|
运行的结果是:
45.98
问题二:先看看下面一段代码:
|
运行的结果是:
45.98
10
也就是说ratio没有成功的赋给stm,那么我们看看stm << ratio后,stm的值是多少:
去掉上面的两行注释,运行结果:
----45.98
45.98
----45.98
10
可见stm << ratio后,stm还是以前的值。这是为什么呢?
很快,就想到了要清空stm。于是:加上清空stm的语句stm.str(""):
|
看看结果:
----45.98
45.98
----
10
ratio的值还是赋不进去,而去掉上面注释的那行str.clear()就OK了。
----45.98
45.98
----11.34
11.34
原来是这样的:
The clear() just clears the failbit and/or eofbit (and the badbit, too, although that is unlikely to be set). In the case of the OP<<, the failbit and eofbit are never set , so the clear is not necessary. It wouldn't hurt, but it wouldn't help here. You can still add a new value.
If you use the extraction operator>> with a stringstream, then you might need to use clear() to allow reading from the stream again (as opposed to writing to it). That's because if you read from the stream it might set the failbit or eofbit and it won't let you read again until you clear those bits.
大致的意思是说:
clear()是清除failbit位和/或eofbit位(还有badbit位)的。当使用操作赋<<时,failbit位和eofbit位是没有设置的,所以,在不用clear的情况下可以继续执行<<操作,加入新值。
但是当使用>>操作符时就要使用clear()才能继续给stringstream读入新值,这是因为>>操作从stringstream中读出数据流时,stringstream会设置failbit和eofbit位,而在没有清这些位之前是读不进去数据的。
参考: