【问题标题】:Not getting exact form of output using terminal没有使用终端获得准确的输出形式
【发布时间】:2015-12-10 11:49:48
【问题描述】:
#include <iostream>
using namespace std;
int main()
{
    int t;
    int n;

    cin>>t;
    while(t--) {
        cin>>n;
        cout<<n<<endl;
    }
}

输入测试文件:

2
1
2

现在当我复制这个输入并将其粘贴到终端时,它会给出如下输出:

2
1
21

2

Process returned 0 (0x0)   execution time : 3.485 s
Press ENTER to continue.

但我希望输出采用 IDE 中给出的以下格式,如代码块。

2
1
1
2
2

将输入复制到终端时是否可以以这种格式显示输出?

【问题讨论】:

  • 您发布的代码为我在终端中产生了正确的输出...
  • 对我来说,它不起作用。你可以看到我的输出。 1 在 2 之后,看起来像 21

标签: c++ terminal output


【解决方案1】:

您的代码为我生成了您想要的正确输入。您的问题很可能是您将输入粘贴到终端中,因此它会立即出现。相反,如果您使用键盘手动输入输入,一个接一个,它应该会产生您想要的视图。

虽然我不知道您为什么要这样做,因为您的终端“输出”的某些行不是输出,而是由于竞争条件的输入。

2 // Input (stdin)
1 // Input (stdin)
1 // Output (stdout)
2 // Input (stdin)
2 // Output (stdout)

编辑:回应对此答案的评论

我希望标准输出在粘贴输入并按 Enter 后具有 2 1 1 2 2。

要实现这一点,您需要了解stdinstdout 之间的区别,而当您运行应用程序时它们都是单独的流,它们都打印到终端。 stdin 通常从键盘读取,这与 stdout 通常打印到终端输出窗口不同。

下面的简单程序将输入和输出分成 2 个独立的for 循环,以便您可以看到区别。

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int t, n, i;
    vector<int> numbers;

    cin >> t;

    // Input
    for (i = 0; i < t; ++i) {
        cin >> n;
        numbers.push_back(n);
    }

    // Output
    cout << t << endl;
    for (vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
        cout << *it << "\n" << *it << endl;
    }
}

当你运行这个程序时,你会看到

$ ./a.out
2
1
2
2
1
1
2
2

在此“输出”中,前 3 个数字来自 stdin,而后 5 个数字来自 stdout,并产生您需要的正确输出。

$ ./a.out
2 // Input (stdin)
1 // Input (stdin)
2 // Input (stdin)
2 // Output (stdout)
1 // Output (stdout)
1 // Output (stdout)
2 // Output (stdout)
2 // Output (stdout)

【讨论】:

  • 我知道如果我将输出一一粘贴,它将产生正确的输出。但这不是我想要的。在竞争性编码期间,我确实需要一次性粘贴整个输入。
  • @shivammitra 这个问题非常不清楚,而且越来越不清楚。您是否希望stdout 具有2 1 1 2 2 或者您是否希望该输出显示在stdinstdout 上,正如我在答案中所示?我认为您需要阅读stdinstdout 之间的区别以及它们在终端中的表示方式。
  • 即使在粘贴输入之后,终端上的输入/输出应该看起来像 2 1 1 2 2 其中一些是输入,一些是输出。在 windows 中复制和粘贴代码块确实可以得到我想要的输出。
【解决方案2】:

您的输入反馈和程序输出之间存在竞争条件。

在您复制和粘贴输入时阻止终端显示您输入的所有内容是不可能的。

如果您延迟程序的输出直到您确定没有输入,您总是可以获得可靠的结果。但是,除非您自己耐心地等待上一行输出,然后再输入下一行,否则您不能反过来。但是您无法使用大多数终端的复制粘贴功能来实现这一点。

【讨论】:

  • 这意味着不可能实现这样的输出。所以,唯一的办法就是把输入一个一个写出来。
猜你喜欢
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2018-06-26
相关资源
最近更新 更多