简体   繁体   English

声明一个固定大小的字符串,然后接受输入

[英]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-> int 上面的代码首先我取一个 int 长度,然后用它来定义字符串的大小,但问题是当我在定义长度后cin>>s时,字符串仍然需要比长度更多的字符,即 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从 stream 中提取字符串

Extracts a string from the input stream is , storing the sequence in str , which is overwritten ( the previous value of str is replaced ).从输入 stream is中提取一个字符串,将序列存储在str中,该序列被覆盖( str的先前值被替换)。 Each extracted character is appended to the string as if its member push_back was called.每个提取的字符都附加到字符串中,就好像它的成员push_back被调用一样。

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.字符串的内容将被替换为您的输入,该输入可以是任何大小,因为字符被附加到字符串中,就好像调用了push_back一样。

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.长答案:您创建了一个保留 3 个字符的空字符串。 operator>> assigned new value to s . operator>>s分配了新值。 Old value, a 3-character capable string is lost.旧值,3 个字符的字符串丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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