Initialize a string
variable that will store the spaces, then add spaces to it by looping.
int n = 3;
string indents;
for (int c = 0; c < n; c++)
indents += " ";
Combining everything in one string,
string s = "This is a string.\n" + indents + "This is a string.\n" + indents + "This is a string\n" + indents;
cout << s;
EDIT:
Since you mentioned that the occurrences or positions of \n
are unknown,
You can use string::find to find the first occurrence of \n
, then add n
spaces after it using string::insert then loop until all occurrences of \n
are found and spaces are added after it.
int n = 3;
string s = "This is a string.\nThis is a string.\nThis is a string\n";
// first occurrence
size_t pos = s.find("\n");
while (pos != string::npos) {
// insert n spaces after \n
s.insert(pos + 1, n, ' ');
// find the next \n
pos = s.find("\n", pos + 1);
}
cout << s;
Output
This is a string.
This is a string.
This is a string.