首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可以这样串流吗?将字符串转换为int?

可以这样串流吗?将字符串转换为int?
EN

Stack Overflow用户
提问于 2011-02-20 13:16:42
回答 5查看 9.8K关注 0票数 2

有可能像这样串流吗?我正在尝试用ifstream阅读并转换它。

代码语言:javascript
复制
string things = "10 11 12 -10";
int i1;
int i2;
int i3;
int i4;
stringstream into;
into << things;
into >> i1;
into >> i2;
into >> i3;
into >> i4;

我期望它是:

代码语言:javascript
复制
i1 = 10
i2 = 11
i3 = 12
i4 = -10

对吗?

同一个stringstream变量可以多次使用吗?

当我尝试的时候,第一次是可以的,但后来的一切都是0。

EN

回答 5

Stack Overflow用户

发布于 2011-02-20 13:24:17

这肯定能行得通。您甚至可以混合类型,如下所示:

代码语言:javascript
复制
string things = "10 Nawaz 87.87 A";
int i;
std::string s;
float f;
char c;

stringstream into;
into << things;
into >> i >> s >> f >> c; //all are different types!

cout << i <<"  "<< s <<"  "<< f <<"  "<< c;

输出:

代码语言:javascript
复制
10 Nawaz 87.87 A

在ideone上演示:http://www.ideone.com/eb0dR

票数 6
EN

Stack Overflow用户

发布于 2011-02-20 13:18:33

它起作用了吗?我这样做的方式是:

代码语言:javascript
复制
istringstream into(things);
into >> i1;

诸若此类。这将产生您发布的输出。

票数 1
EN

Stack Overflow用户

发布于 2011-02-20 13:28:38

您发布的内容与Jeremiah使用istringstream的解决方案一起工作。但是也可以考虑使用scanf系列的函数(对于几个int来说没有太大的区别,但是对于更高级的输入,使用scanf可能比摆弄流操纵器简洁得多):

代码语言:javascript
复制
string things = "10 11 12 -10";
int i1, i2, i3, i4, i5, i6;
sscanf(things.c_str(), "%d %d %d %d", &i1, &i2, &i3, &i4);

您的示例在那之后只给出0的原因是因为一旦提取-10,stringstream缓冲区就是空的:在提取更多之前,您必须在缓冲区中插入更多。您可以多次使用同一个stringstream实例,但每次都需要充分使用缓冲区,或者在向缓冲区中插入下一项之前认识到缓冲区中还有更多内容:

代码语言:javascript
复制
string things = "10 11 12 -10", temp;
int i1, i2, i3, i4;
stringstream into;
into << things; //buffer is now "10 11 12 -10"
into >> i1; //buffer is now " 11 12 -10"
into >> i2; //" 12 -10"
into >> i3; //" -10"
into >> i4; //""

//more code here...

//come back and use the instance again
into << "more: 1 2 3"; //"more: 1 2 3"
into >> temp; //temp is "more:"; into's buffer is " 1 2 3"
into >> i1; //buffer is " 2 3"

//more code here...

//reuse into once again
into << "4 5 6"; // buffer is now " 2 3 4 5 6"
into >> i1; //i1 gets the 2 from before, not the 4 just inserted; buffer now " 3 4 5 6"
into >> i2; //i2==3; buffer is " 4 5 6"

此外,ios ( stringstream继承自它)还定义了!操作符和到void*的强制转换,以便您可以方便地检查提取是否失败(从技术上检查是否设置了failbitbadbit,我相信当缓冲区中没有足够的内容时,failbit将与eofbit一起设置):

代码语言:javascript
复制
string things = "10 11 12 -10";
int i1, i2, i3, i4;
stringstream into;
into << things;
into >> i1 >> i2 >> i3 >> i4;
if (into >> i5) {
    cout << "extraction to i5 succeeded" << endl;
}
if (!(into >> i6)) {
    cout << "extraction to i6 failed" << endl;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5055381

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档