使用 cin 读取大型输入时程序冻结



我在使用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 < input.in运行时,其中 input.in 是保存上述格式的所有输入的文件,然后程序运行良好并且不再冻结。

问题解决了。问题不在于cin函数,而在于我为程序提供输入的方式。将大量的输入粘贴到剪贴板上,然后在运行程序时将其作为参数放在终端中,这是问题所在。当程序按./program < input.in运行时,其中"input.in"是以上述格式保存所有输入的文件,然后程序运行良好并且不再冻结。

最新更新