-5

While I learned C++ I challenged sample problems in which each 1 in stdin will move right in stdout. In sample answer,T(4,0) is defined. As I am beginner, I couldn't understand what is T(4,0). is this different from normal arrays? Thanks

sample answer

#include<bits/stdc++.h>
using namespace std;
int main(){
  string S;
  cin >> S;
  string T(4,0);
  T[0]='0';
  T[1]=S[0];
  T[2]=S[1];
  T[3]=S[2];
  cout << T;
}
Heisenberg
  • 4,787
  • 9
  • 47
  • 76
  • 3
    Don't learn from random websites, they suck. Read a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Passer By Apr 22 '22 at 05:53
  • 3
    [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) As well as [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Some programmer dude Apr 22 '22 at 05:55

2 Answers2

2

std::string has several constructors. In this case:

basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() );

(You don't provide an argument for alloc so the default is used. Don't worry about it.)

This constructor has the following effects:

  1. Constructs the string with count copies of character ch. [This constructor is not used for class template argument deduction if the Allocator type that would be deduced does not qualify as an allocator. (since C++17)]

So this creates a std::string with 4 characters in it, and each character is 0, aka '\0', aka null.

Nathan Pierson
  • 5,461
  • 1
  • 12
  • 30
2

Since T is a std::string, it's the constructor of std::string https://en.cppreference.com/w/cpp/string/basic_string/basic_string

In this case, it's the constructor under 2):

basic_string( size_type count, CharT ch,
              const Allocator& alloc = Allocator() );

(alloc is a default argument and not needed to be supplied by you.)
It creates a string with count characters and every character is initialized to ch.

In your case, it's a string with 4 characters, all initialized to whatever ascii value 0 has. The \0 character.

Raildex
  • 3,406
  • 1
  • 18
  • 42