cout return twice a string of char

Viewed 152

The output of the below code is

Toto
TotoToto

but I would hope just

Toto
Toto

Why the second cout repeat the string in the output?

I'm using g++ version 7.5.0 on Ubuntu, I'm not sure if this is relevant.

The code is the following:

#include<iostream>

using namespace std;

int main(){

  char c1[] = "Toto";
  char c2[4] = {'T','o','t','o'};


  cout << c1 << endl;
  cout << c2 << endl;


  return 0;

}
1 Answers

When you stream out a character array, it must - by convention - be null terminated, otherwise you have undefined behaviour.

Change c2 as follows and it will start working as hoped:

char c2[5] = {'T','o','t','o', '\0'};

In the case of c1, it assumes you'll want an implicit null appended and sizes c1 automatically to allow space for that, so if you use sizeof or std::extent<> to get the size of c1 you'll see it's 5 bytes.

Drew's comment suggests explaining about the decay of arrays to pointers when calling functions, so here goes. When you write:

cout << c2;

The compiler calls the function std::ostream& operator<<(std::ostream&, const char*). The array c2 decays to a char*, allowing the function to be matched and called, but in doing so all knowledge of the text length is lost. The function implementation expects you to follow the convention of having a null terminator after the text to be streamed. If you want explicit control of how many characters should be printed, you can use e.g. std::cout.write(c2, 3). std::strings also work more intuitively - beginning programmers should prefer using std::strings to store and manipulate text.

Related