Reputation: 63
#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,
Upvotes: 0
Views: 819
Reputation: 217275
Maybe you want:
std::string s(length, '\0');
std::cin.get(s.data(), s.size());
Upvotes: 1
Reputation: 14589
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.
Upvotes: 0
Reputation: 44838
The documentation says:
istream& operator>> (istream& is, string& str);
Extract string from stream
Extracts a string from the input stream
is
, storing the sequence instr
, which is overwritten (the previous value ofstr
is replaced). Each extracted character is appended to the string as if its memberpush_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.
Upvotes: 0