0

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;
}

When I take input using this code, output shows like this

12
  • 6
    C or C++? C does not have strings - only nul terminated char arrays. So you must use a character array. Commented Feb 12, 2018 at 12:44
  • Yes, but why? Commented Feb 12, 2018 at 12:44
  • it doesn't work properly. --> Can you elaborate it a bit? Commented Feb 12, 2018 at 12:47
  • 1
    str.c_str() is read-only. And not allocated/empty... UB. use std::cin instead. std::string supports it natively Commented Feb 12, 2018 at 12:47
  • 1
    You are not supposed to mix C and C++ like that. It's basically impossible to make the scanf line 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. scanf doesn't do that. std::cin does so you can do std::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. Commented Feb 12, 2018 at 12:50

1 Answer 1

1

You are trying to write in a zone which is read only e.g. str.c_str(). What you want to do is either :

 std::cin >> str;

or if for a specific reason you have to use scanf. Since C++17 you can do :

  str.data()

Which returns a modifiable memory zone.

Edit : as @nwp said, you have to call str.resize(size) to because the size of the string is 0 before that.

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

2 Comments

Modifiable yes, but with size 0, so not very useful. You would need to call str.resize(some_magic_number); first.
@nwp True, I don't see the point of using scanf here so I omitted that detail. Thanks I'll edit to match your comment

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.