It is necessary to display an array of 20 q. But instead he prints: qqqqqqqqqqqqqqqqqqqqММММT?HЎhэУ . How to fix it?

 #include "pch.h" #include <iostream> #include <Windows.h> using namespace std; int main(int argc, const char * argv[]) { setlocale(LC_CTYPE, "rus"); char tt[20] = { 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q' }; cout << tt << endl; cin.get(); return 0; } 
  • Judging by the variety of answers, we need to add a code-golf tag :) - Harry

4 answers 4

A C-style string ( char array) must end with a null character.

Option 1.

 char tt[21] = { 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', '\0' }; 

Option 2.

 for(auto c: q) cout << c; cout << endl; 

    Use std::string_view

      #include <iterator> #include <string_view> ... char tt[20] = { ... }; std::cout << std::string_view(tt, std::size(tt)) << std::endl; 
        #include <cstdlib> #include<iostream> using namespace std; int main(){ char chr[90] = "qq qq qq";//объявили массив символов и проинициализировали cout << chr; return 0; } 

      Add as many q as you need

        And I want to participate! :)

         copy(begin(tt),endd(tt), std::ostream_iterator<char>(cout,"")); 

        and

         cout << string(begin(tt),end(tt));