关于用scanf()输入string类型引起的问题


我们都知道scanf()是可以输入string类型的:

如:

#include 
#include <string>
#include
using namespace std;
int main()
{
    string a;
    a.resize(6); //需要预先分配空间,超出空间会被截取
    scanf("%s", &a[0]);
    cout << a;//用printf("%s",a.c_str())也可以输出
    return 0;
} 

这种情况是一定不会出错的。

但还有一些人认为可以这样:

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

int main(){
string a;a.resize(6); 
scanf("%s",a.c_str());
printf("%s",a.c_str());

return 0;
}

这样子并没有预先开辟空间:

运行结果如下图:

 可以看到这是可以的,但这样子会出现一些潜在的危险,如果我们将

printf("%s",a.c_str());改为cout<
则输出为空,如下图:

 在一些情况下我们用scanf()利用刚才上述的方法输入string类型时(scanf("%s",a.c_str());),且并没有开辟空间,如果将输入的string赋值给其他string类型时,则会出现赋值为空。但仅可以通过

printf("%s",a.c_str());进行输出(cout<
因此在对string用scanf()进行输入时一定要进行开辟空间。