Home > Mobile >  Use just LF (line feed) not NL (new line)
Use just LF (line feed) not NL (new line)

Time:02-01

Is there a way in C to get to the next line without CR (carriage return), essentially moving a line down.

std::cout << "Hello\nworld!"

output should be something like this

Hello
     world!

I also tried form feed but it prints Hello♀world!

EDIT-

Looks like I'm not very clear, so let me explain a bit more.

Windows a long time ago used CRLF for new line i.e \r\n. Here \r is meant to move cursor to far left of screen while \n moves cursor a line down. However, \n when printed brings cursor to left and a line down. I just want the initial role of \n back which just moving a line down at same column...

CodePudding user response:

The correct solution would be moving the cursor manually, for example with ANSI sequences if on a capable terminal. Or if you can be sure that the next line is blank or begins with all spaces then just echo the spaces manually as Jeff said:

std::cout << "Hello\n     world!";

In case you're using a *nix terminal then you can control the LF → CRLF translation with stty:

user@HOSTNAME:~$ echo -e "Hello\nworld"
Hello
world
user@HOSTNAME:~$ stty -opost # Disable LF → CRLF translation
user@HOSTNAME:~$ echo -e "Hello\nworld"
Hello
     world
          user@HOSTNAME:~$ stty opost
user@HOSTNAME:~$ stty -onlcr # Disable LF → CRLF translation
user@HOSTNAME:~$ echo -e "Hello\nworld"
Hello
     world
          user@HOSTNAME:~$

See How can I configure the Linux terminal to only line feed (and not carriage return) when outputting a "\n"?

CodePudding user response:

It sounds like you want the output cursor to go to the next line, but stay in the same column, like this:

Hello
     world!

Unfortunately, most terminals I have used will interpret a newline \n character as a combination of a newline and a carriage return. Therefore, your program must print a newline, and then enough spaces to reach the column you want:

std::cout << "Hello\n     world!";
  •  Tags:  
  • Related