0

I'm trying to generate a string of 50 dots. I have the following code:

#include <string> using namespace std; int main(){ string s(".",50); cout << s; } 

and the output is:

.vector::_M_realloc_insert$C����pX�% 

The string s doesn't store . 50 times, but some other part of memory. A leak happened, and I have no idea how.

What went wrong? How do I go about generating a string of length n consisting only of dots? In general, I want to do in c++ what in python would be done by "c"*n.

Thank you.

2
  • 1
    You should read the documentation more carefully. The constructor you want is std::string s(50, '.');. And next time, please remove anything irrelevant (i.e. 95% of it) from the code you post, see minimal reproducible example. Commented Dec 22, 2022 at 22:32
  • ok ty. i didnt know what was the minimal reproducible data since the print out referred to vec, etc. removed everything else. Commented Dec 22, 2022 at 22:44

1 Answer 1

5

Your example could be a whole lot shorter, and still have the same problem.

The problem is that with the std::string constructor you use, the length is the length of the string ".", not how long the std::string should be. Since "." is not 50 characters long, you will have undefined behavior.

From the linked reference for constructor number 4 (the one you use):

The behavior is undefined if [s, s + count) is not a valid range

There s is the string "." and count is the value 50.

The constructor I guess you want to use is the one taking a single character instead of a string (number 2 in the linked reference):

std::string s(50, '.'); // Fill string with 50 dots 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.