0

I'm trying to learn how to get started learning to do C++ coding on Ubuntu. I created a file called text.cpp with the following contents:

#include <stdio.h>
int main ()
{
printf("Hello World!");
}

I compiled it using the following line:

gcc test.c -o mytest

However, when I run ./mytest the string "Hello World!" shows up in front of the command prompt like this.

Hello World!mbishop@ubuntu:~bin$

Why is this happening and how can I get it to print after the command prompt. For example, like when you type echo "Hello Wolrd!".

charlie
  • 187
  • 4
  • 15

2 Answers2

1

you can add a line break after Hello World! like so:

printf("Hello World!\n");

EDIT

You could also use puts:

puts("Hello World");

And since you ask why, it is only because printf writes output to stdout without adding a new line. If you use puts, it will write the output and add a newline by default. Hence, puts() moves the cursor to next line.

scharette
  • 9,437
  • 8
  • 33
  • 67
0

The problem is a missing line break.

You could use printf or puts. However, stdio.h is a C header, not idiomatic C++. See this answer. If your aim is to code in good C++ style, the following would be more appropriate.

#include<iostream>

int main() {
    std::cout << "Hello World!" << std::endl;
}