0

Why the result of my code is not true. Is it because scanf function?

#include <cstdio>
#include <string>

using namespace std;

int main(){
    string s, t;
    scanf("%s", s.c_str());
    scanf("%s", t.c_str());
    int a = s.find(t);
    while(a > -1){
        s = s.erase(a, t.length());
        a = s.find(t);
    }
    printf("%s", s.c_str());
}

1 Answers1

2

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.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30