String类可以用cin流式读取。
在用scanf读取时,必须声明长度。不声明长度,直接scanf会出现运行时错误。
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
string a;
a.resize(100); //需要预先分配空间
scanf("%s", &a[0]);
puts(a.c_str());
return 0;
}
扩展资料:
C++11标准规定:basic_string的元素是连续存储的。即对于basic_string s,有:&*(s.begin() + n) == &*s.begin() + n,其中n属于[0, s.size())。
换句话说,指向s[0]的指针即为指向CharT[]数组的首元素指针。C++11已经禁止了写入时复制(copy-on-write)的实现,因为存在多线程安全问题。一般都采用了小字符串优化(SSO)实现,如Visual C++:
union _Bxty { // storage for small buffer or pointer to larger one _Elem _Buf[_BUF_SIZE]; _Elem *_Ptr; } _Bx; size_type _Mysize; // current length of stringsize_type _Myres; // current storage reserved for string
GCC从版本5开始,std::string不再采用COW策略。
C++17标准规定,basic_string是AllocatorAwareContainer, SequenceContainer与ContiguousContainer。