用scanf、printf输入输出string型字符串

    c语言里是没有string型的,string在c++里面。有的时候在c++里要用scanf、printf输入输出string型字符串,这是可以实现的,不过要做一点处理。

具体操作看代码:

#include<cstdio>
#include<string>
using namespace std;
int main()
{
    int n;
    string str1;
    scanf("%d",&n);
    str1.resize(n);  //给字符串str1预留足够的空间
    scanf("%s",&str1[0]);  //不能用&str1
    printf("%s
",str1.c_str());  //用str1自带的成员函数c_str()把c++里的string型字符串转换成c字符串
    return 0;
}

结果如下:

原文地址:https://www.cnblogs.com/buanxu/p/12781937.html