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,

kaylum
  • 13,833
  • 2
  • 22
  • 31
ArcaneAce
  • 63
  • 3

3 Answers3

1

Maybe you want:

std::string s(length, '\0');
std::cin.get(s.data(), s.size());
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • `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` instead, and then copy it to a `std::string` afterwards. – Remy Lebeau May 09 '20 at 15:39
  • @RemyLebeau: fixed. – Jarod42 May 09 '20 at 19:27
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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
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.

Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42