I don't want to declare character array. I want to declare string. And take input and show output of that string using scanf and printf. I have tried to do it this way that's shown below but it doesn't work properly. How to do it in proper way?
#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()is read-only. And not allocated/empty... UB. usestd::cininstead.std::stringsupports it nativelyscanfline correct because it reads an arbitrary amount of data into a buffer, so you need an arbitrarily big buffer which means you must make the buffer bigger while reading.scanfdoesn't do that.std::cindoes so you can dostd::cin >> str;. You should try to use the tools that do exactly what you want instead of hacking on tools that are made for a different purpose.