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());
}
5
  • 5
    That should give you compile warnings to start with. c_str returns a const char* while %s expects a non-const pointer Commented May 30, 2022 at 14:04
  • 3
    And you simply cannot directly write to a std::string via C IO functions Commented May 30, 2022 at 14:05
  • 3
    There is no reason to assume that strings s and t have buffers large enough to take the scanned string. Commented May 30, 2022 at 14:05
  • 2
    why do you want to do this instead of the perfectly legal and working C++ std::cin >> s >> t; ? Commented May 30, 2022 at 14:09
  • 1
    Does this answer your question? Read into std::string using scanf Commented May 30, 2022 at 14:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Note, also, that if scanf reads, for example, only one character, s.size() is still 4096. +1.
Okay thank you for the answer and your suggestion churill and pete becker. I decide to use cin because that is still not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.