0
#include<bits/stdc++.h>
using namespace std;
int main(){
    int length;
    cin>>length;
    string s(length,'\0');
    cin>>s;
    cout<<s;
}

int the code above firstly im taking a int length and then using it to define the size of the string but the issue is that when i cin>>s after defining length the string still takes more char's than length i.e OUTPUT->

3
Hello
Hello

this should not happen after defining length of the string,

1

3 Answers 3

2

Maybe you want:

std::string s(length, '\0');
std::cin.get(s.data(), s.size());
Sign up to request clarification or add additional context in comments.

1 Comment

s.c_str() returns a pointer to const data, so you can't fill the string using that pointer. Use s.data() (C++17 and later) or &s[0] to get a pointer to writable memory. Otherwise, use a std::vector<char> instead, and then copy it to a std::string afterwards.
0

The documentation says:

istream& operator>> (istream& is, string& str);

Extract string from stream

Extracts a string from the input stream is, storing the sequence in str, which is overwritten (the previous value of str is replaced). Each extracted character is appended to the string as if its member push_back was called.

So, when you're doing:

cin>>s;

the contents of the string are being replaced with your input that can be of any size because characters are being appended to the string as if push_back was called.

Comments

0

Short answer: yes, it should. You misintepret meaning of instructions you give, without regard to documentation.

Long answer: You had created an empty string with reservation of 3 chars. operator>> assigned new value to s. Old value, a 3-character capable string is lost.

Comments

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.