-2

I've recently learnt about std::substr() by searching on Google. I saw a code something like this:

std::string s = "This is an example string";
std::string s1 = s.substr(11, 7);
std::cout << s1 << std::endl;

Now if I try to take input using scanf() function (instead of using std::cin), the program crashes during runtime. Doesn't std::string support using scanf() function?

Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
  • 1
    The question isn't very clear to me. Are you trying to get input from a string, for from the standard input, and what does substr have to do with your question? Basically I need to know what you are trying to do, then I could say how to do it. – john Feb 08 '18 at 08:23
  • 2
    `substr` doesn't work on `cin`, it works on `string`. – john Feb 08 '18 at 08:25
  • 7
    [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h/31816096#31816096) – milleniumbug Feb 08 '18 at 08:31
  • 1
    You really ought to avoid `using namespace std` - it is a bad habit to get into, and [can silently change the meaning of your program](/q/1452721) when you're not expecting it. Get used to using the namespace prefix (`std` is intentionally very short), or importing *just the names you need* into the *smallest reasonable scope*. – Toby Speight Feb 08 '18 at 15:56
  • 'scanf()' with an unbounded `%s` or `%[` is as dangerous as `gets()` (for the same reason). And neither of them want a `std::string` as the corresponding argument (they take a `char *`). – Toby Speight Feb 08 '18 at 15:58

1 Answers1

4

scanf() belongs to a family of C functions that, being part of the C language rather than C++, offers no direct support for std::string and works instead with null terminated character strings.

If you are using C++, you should generally prefer std::string over null terminated terminated character strings and the input/output library over printf()/scanf() library functions.

Component 10
  • 10,247
  • 7
  • 47
  • 64