用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\n",str1.c_str());  //用str1自帶的成員函數c_str()把c++里的string型字符串轉換成c字符串
    return 0;
}

結果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM