string居然也可以用<<和>>
2019-04-11 09:17
447 查看
最近在项目工程中碰到一段代码, 颇为费解, string居然也可以用 <<和>>, 于是我单独写了个小程序测了一下:
#include <iostream> #include <string> using namespace std; int main() { int a = 1; string s; s << a; return 0; }
编译错误:error: no match for 'operator<<' in 's << a'
这是正常的。
但为什么在工程项目中就可以呢? 请教了一下别的同事, 才发现, 是对string进行了扩展, 在项目工程中写测试代码, 部分代码如下:
// 工程中的部分代码 int main() { int a = 1; float b = 2.0f; bool c = true; string d = "hello world"; string s; s << a; s << b; s << c; s << d; cout << "size is " << s.size() << endl; int a2; float b2; bool c2; string d2; s >> a2; s >> b2; s >> c2; s >> d2; cout << a2 << endl; cout << b2 << endl; cout << c2 << endl; cout << d2 << endl; cout << "size is " << s.size() << endl; return 0; }
结果为:
size is 22
1
2
1
hello world
size is 0
可见, string在这里具备了类似流的功能。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接
您可能感兴趣的文章:
相关文章推荐
- <string> 与<string.h>、<cstring>的区别
- 【转】<string> <string.h> <cstring>的区别
- <string> 与<string.h>、<cstring>的区别
- <p>标签为何不可以包含<div>标签
- <string> 与<string.h>、<cstring>的区别
- 在java代码里写Map<String, ?>和Map<String, Object>都是可以用的,他们两个有什么区别?
- <string> 与<string.h>、<cstring>的区别
- string也可以用 <<和>>吗?
- 【C++】<string> 与<string.h>、<cstring>的区别
- <string> <string.h>
- 你还可以把链接向两端对齐: ← Older Newer → <nav aria-label="..."> <ul class="pager"> <li class="previous">
- <string> 与<string.h>、<cstring>的区别
- <string> 与<string.h>、<cstring>的区别
- 类型“string”必须是不可以为 null 值的类型才能用作泛型类型或方法“System.Nullable<T>”中的参数“T”
- 有两种分别用<bgsound>和<embed></embed>标签,当用<embed>插入背景音乐时可以设置宽度和高度为0,隐藏播放器。
- <<离散数学>>for其实可以非常酷
- AutoCompleteTextView 自定义adapter。 可以添加List<Map<String,Object>>
- <<软件性能测试与LoadRunner实战>>可以在网上和书店买到了
- 认识PHP代码标识 想在页面中编写PHP代码非常容易,如下面代码: <?php echo "想学习php吗?来慕课网吧"; ?> 就像你可以编写JavaScript脚本语言需要写在<scri
- <笔记><算法导论> 假设求解问题的算法需要f(n)毫秒,对下表中的每个函数f(n)和时间t,确定可以在时间t内求解的问题的最大规模n。