使用 cin 读取大量输入时程序冻结
Program freezes when reading large inputs using cin
我在使用 cin
读取程序中的输入时遇到问题。输入如下所示:
5 2
10 17 17 17 37
其中 5 是项目数,2 是分隔线数(与此问题无关)。两行都以行尾字符结束。
问题是当项目的数量大于大约 500 并且数字也变大时(而不是 17,比如 50356),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' 是包含上述格式的所有输入的文件时,程序运行良好并且不再冻结。
我在使用 cin
读取程序中的输入时遇到问题。输入如下所示:
5 2
10 17 17 17 37
其中 5 是项目数,2 是分隔线数(与此问题无关)。两行都以行尾字符结束。
问题是当项目的数量大于大约 500 并且数字也变大时(而不是 17,比如 50356),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' 是包含上述格式的所有输入的文件时,程序运行良好并且不再冻结。