简体   繁体   English

停止新行 C++ cin

[英]Stop new line for C++ cin

In C++, iostream automatically puts in a new line after cin.在 C++ 中,iostream 自动在 cin 之后换行。 Is there a way to get rid of this?有没有办法摆脱这个?

I want use iomanip to format information into a table, like so:我想使用 iomanip 将信息格式化为表格,如下所示:

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.在此换行符出现在控制台之前,您无法从cin读取您的号码,因为换行符是导致控制台首先将您的输入移交给程序的原因。 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".如果你真的想让你的输入和你的 output 在同一行,你需要找到一种方法来“写到上一行”。 How that works depends on your console (see also How to rollback lines from cout? ).它的工作方式取决于您的控制台(另请参阅如何从 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.没有标准的方法可以做到这一点,因为cincout没有义务连接到控制台或任何类似的东西,所以不清楚“写入上一行”甚至意味着什么。

'endl' makes a new line just don't use it. 'endl' 换行只是不要使用它。

cout << num; cout << 数;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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