Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

visual studio code - Can't we declare a string datatype in C++ with its size?

I was declaring a string in C++ and got an error.

#include<iostream>
#include<string>

using namespace std;

int main(){

    int t;
    cin>>t;

    while(t--){
        int n;
        cin>>n;

        string encoded(10);

The error says: no instance of constructor "std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string [with _CharT=char, _Traits=std::char_traits<char>, _Alloc=std::allocator<char>]" matches the argument list -- argument types are: (int)C/C++(289)

What is the meaning of this error and why can't we declare a string datatype like this?

question from:https://stackoverflow.com/questions/65542142/cant-we-declare-a-string-datatype-in-c-with-its-size

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

std::string constructors can be tricky. It helps to use a good reference, such as the cppreference wiki.

It's not clear exactly what "a string of length 10" should be without providing other details. You might want,

  • ten whitespace characters, like std::string variable1( 10, ' ' );
  • a string variable which is empty, but can get up to ten characters without allocating additional memory, like std::string variable1; variable1.reserve( 10 );

If you use the generic container methods of std::string such as resize, or pass '' NUL characters instead of whitespace, then those NULs will be treated as part of the string. That could break usual text-oriented functionality and cause conflicting results from C and C++ based logic.

If you really want exactly ten characters starting as NUL, and not a class with an append operation and such, then try an array like std::array<char,10> variable1 or char variable1[10].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...