Chinaunix首页 | 论坛 | 博客
  • 博客访问: 265333
  • 博文数量: 74
  • 博客积分: 1470
  • 博客等级: 上尉
  • 技术积分: 793
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-25 21:01
文章分类

全部博文(74)

文章存档

2011年(1)

2010年(32)

2009年(32)

2008年(9)

我的朋友

分类: LINUX

2009-08-13 15:09:27

问题一:在C++中,怎么把string类型的变量变成int或double呢?
我们知道在C中有atoi、atof,那在C++中怎么办呢?总不能把string转化成char*,然后再用atoi、atof吧!
有一个办法可以,就是用stringstream,直接上代码:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
    string num = "45.98";
    stringstream stm;
    double x;

    stm << num;
    stm >> x;
    cout << x << endl;
     
    return 0;
}


运行的结果是:
45.98

问题二:先看看下面一段代码:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
    string num = "45.98";
    string ratio = "11.34";
    stringstream stm;
    double x;
    double y=10;

    stm << num;
// cout << "----" << stm.str() << endl;
    stm >> x;

    cout << x << endl;

    stm << ratio;
// cout << "----" << stm.str() << endl;
    stm >> y;
    cout << y << endl;

    return 0;
}


运行的结果是:
45.98
10
也就是说ratio没有成功的赋给stm,那么我们看看stm << ratio后,stm的值是多少:
去掉上面的两行注释,运行结果:
----45.98
45.98
----45.98
10
可见stm << ratio后,stm还是以前的值。这是为什么呢?
很快,就想到了要清空stm。于是:加上清空stm的语句stm.str(""):

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
    string num = "45.98";
    string ratio = "11.34";
    stringstream stm;
    double x;
    double y=10;

    stm << num;
    cout << "----" << stm.str() << endl;
    stm >> x;
    cout << x << endl;


    stm.str("");
// stm.clear();

    stm << ratio;
    cout << "----" << stm.str() << endl;
    stm >> y;
    cout << y << endl;

    return 0;
}


看看结果:
----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位,而在没有清这些位之前是读不进去数据的。

参考:


阅读(1413) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~