简体   繁体   中英

Stop new line for C++ cin

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;
}

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.

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

cout << num;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM