ArcaneAce
ArcaneAce

Reputation: 63

Declaring a string with fixed size and then taking input

#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

Answers (3)

Jarod42
Jarod42

Reputation: 217275

Maybe you want:

std::string s(length, '\0');
std::cin.get(s.data(), s.size());

Upvotes: 1

Swift - Friday Pie
Swift - Friday Pie

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

ForceBru
ForceBru

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 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.

Upvotes: 0

Related Questions