scanf will simply write to any buffer you give it. It doesn't know that the buffer belongs to a std::string, nor does it know how large the buffer is. Also you are writing to a const char* - that points to a readonly buffer of unknown size. Your code has undefined behaviour.
Yes, it is possible to directly write to the internal buffer of a std::string using std::string::data(). But when you do this, you need to make sure the buffer is large enough using resize() or constructor #2:
int main(){
string s(4096, '\0');
scanf("%s", s.data());
...
}
You end up with the same problem as if you were using a plain char[].
The C++-way std::cin >> s; or std::getline(std::cin, s) would be much easier and safer.
c_strreturns aconst char*while%sexpects a non-constpointerstd::stringvia C IO functionssandthave buffers large enough to take the scanned string.std::cin >> s >> t;?