【问题标题】:Program freezes when reading large inputs using cin使用 cin 读取大型输入时程序冻结
【发布时间】:2018-01-08 20:09:56
【问题描述】:

我在使用cin 读取程序中的输入时遇到问题。输入如下所示:

5 2
10 17 17 17 37

其中 5 是项目数,2 是分隔线数(与此问题无关)。两行都以行尾字符结束。

问题是当项目的数量变得大于大约 500 并且数字也变得更大(而不是像 50356 这样的 17 个)时,cin 在读取大输入时在某处停止(它只是冻结整个程序) .奇怪的是,它在小输入上完美运行(我的程序完全符合我的预期),但在较大输入上却不行。我还想以 > 5000 的输入大小运行它。我不知道为什么它不起作用。也许存在缓冲区问题,我需要刷新。解决方案可能非常简单。

void fill()
{
    cin >> numberOfItems;
    cin >> dividers;

    vector<unsigned long int> roundedSum;
    roundedSum.resize(numberOfItems);
    unRoundedSum.resize(numberOfItems);
    currentSum.resize(numberOfItems);
    updatedSum.resize(numberOfItems);

    unsigned long int tempValue;
    cin >> tempValue;

    roundedSum[0] = roundValue(tempValue);
    unRoundedSum[0] = tempValue;

    for (unsigned long int i = 1; i < numberOfItems; ++i){
        cin >> tempValue;
        tempValue += unRoundedSum[i - 1];
        unRoundedSum[i] = tempValue;
        roundedSum[i] = roundValue(unRoundedSum[i]);
    }
    currentSum = roundedSum;
    updatedSum = roundedSum;
}

编辑:问题已解决 问题不在于cin 函数,而在于我给程序输入的方式。将大量输入粘贴到剪贴板上,然后在运行程序接缝时将其作为参数放在终端中是问题所在。当以./program &lt; input.in 运行程序时,其中 input.in 是以上述格式保存所有输入的文件,然后程序运行良好并且不再冻结。

【问题讨论】:

  • 您确定将所有 500 项都传递到标准输入吗?
  • 是的,我确定。我正在使用 ./program 之类的 linux 终端运行程序,然后输入。它适用于较小的输入,但不适用于较大的输入
  • 也许它不是 cin,而是你在循环中所做的工作的复杂性,这让你放慢了速度。请尝试注释掉循环中完成的工作,然后尝试读取值。
  • 尝试for (size_t i = 1; i &lt; numberOfItems &amp;&amp; cin &gt;&gt; tempValue; ++i){ 并从循环内部摆脱cin &gt;&gt; tempValue;
  • 我觉得非常愚蠢,但显然用剪贴板粘贴是问题所在。如果我将程序作为“./program

标签: c++ input cin


【解决方案1】:

问题解决了。问题不在于cin 函数,而在于我给程序输入的方式。将大量输入粘贴到剪贴板上,然后在运行程序接缝时将其作为参数放在终端中是问题所在。当以./program &lt; input.in 运行程序时,其中'input.in' 是包含上述格式的所有输入的文件,然后程序运行良好并且不再冻结。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2019-02-22
    相关资源
    最近更新 更多