-2

I'm struggling with trying to implement a C++ code solution that will allow me to insert a newline (i.e. a string literal '\n') towards the end of a std::string, and not at the very end as most implementations show.

For example, I want to insert a '\n' just -1 characters before the very end itself. So if the string was 100 characters long (poor analogy I know), then I'd like to insert the string literal at the 99th character in a clean, easily readable manner.

Thanks!

1
  • 1
    Perhaps this std::string reference could be of help? It should at least tell that there's a function ti insert characters into a string at an arbitrary (but valid) position. Commented Aug 7, 2019 at 6:47

1 Answer 1

3

Here's one way:

std::string test{"abcdef"}; if (!test.empty()) test.insert(test.length() - 1, "\n"); 

and here's one based on iterators:

if (!test.empty()) test.insert(std::prev(test.end()), '\n'); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you kindly, none of the examples were near that simple.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.