[英]How to use scanf and printf for string in C language
我不想聲明字符數組。 我想聲明字符串。 然后使用scanf和printf進行輸入並顯示該字符串的輸出。 我試圖這樣做,如下所示,但無法正常工作。 如何以正確的方式做到這一點?
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str;
scanf("%s", str.c_str());
printf("%s", str.c_str());
return 0;
}
您正在嘗試在只讀區域中寫入內容,例如str.c_str()。 您想要做的是:
std::cin >> str;
或者由於特定原因而必須使用scanf。 從C ++ 17開始,您可以執行以下操作:
str.data()
它返回一個可修改的存儲區。
編輯:如@nwp所說,您必須調用str.resize(size),因為在此之前字符串的大小為0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.