-1

In C++, iostream automatically puts in a new line after cin. Is there a way to get rid of this?

I want use iomanip to format information into a table, like so:

cin        cout
0.078125   3DA00000
-8.75      C10C0000
23.5       41BC0000

(random numbers)


example code:

#include <iostream>
using namespace std;

int main()
{
    int num;

    cin >> num; //now a new line.
    cout << num << endl;

    return 0;
}
  • 3
    It's not clear what you are asking. Posting your code might be helpful. – R Sahu Apr 23 '15 at 02:42
  • yes please post your code – Sean Apr 23 '15 at 02:42
  • If you have two independent questions, you should ask them in two separate posts. –  Apr 23 '15 at 02:43
  • is this clearer now? – Gᴇᴏᴍᴇᴛᴇʀ Apr 23 '15 at 02:47
  • 1
    `cin` only reads your input -- how can it be adding a newline? Perhaps you are confusing this with the `endl` in cout. – nneonneo Apr 23 '15 at 02:47
  • I would assume it is in the library – Gᴇᴏᴍᴇᴛᴇʀ Apr 23 '15 at 02:48
  • 3
    It's not even the library... it's the combination of your terminal program and operating system... the C++ program doesn't see the input until you press Enter because it's line buffered. You need to use some terminal escape codes to disable automatic echoing of typed characters *by the terminal*, optionally disable line buffering, then take control of echoing inside the C++ code: using ncurses is the sanest way to do that. Alternatively, for a less portable but lightweight option, rely on escape sequences supported by your specific terminal to get and set cursor coordinates. – Tony Delroy Apr 23 '15 at 02:51

2 Answers2

2

You presumably pressed the return key to send your input from the command line to your program's standard input. That's where the newline is coming from. You can't read your number from cin before this newline appears in the console, because the newline is what causes the console to hand your input over to the program in the first place. You could, as a user, configure your console (or whatever is running your program) to act differently, but there's no way for the program itself to force such behavior.

If you really want to have your input and your output on the same line, you need to find a way to "write to the previous line". How that works depends on your console (see also How to rollback lines from cout?). There is no standard way to do this because cin and cout are in no way obligated to be attached to a console or anything resembling one, so it is not clear that "writing to the previous line" even means anything.

Community
  • 1
  • 1
alcedine
  • 909
  • 5
  • 18
0

'endl' makes a new line just don't use it.

cout << num;

Borki
  • 1
  • 2