简体   繁体   中英

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 ie OUTPUT->

3
Hello
Hello

this should not happen after defining length of the string,

Maybe you want:

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM