我有一个仅包含一个整数的文本文件,即使它应该包含至少两个整数。
我需要读取第一个值(2
在这种情况下),并将其存储到中positiveIntegerOne
。如果文件不包含任何数字,则显示错误消息“输入文件存在但没有值”。然后,读取第二个值(在这种情况下,第二个值不存在)。如果第二个值存在,则将其存储到中positiveIntegerTwo
,如果该数字不存在,则显示错误消息“输入文件的值具有奇数个。”
这是逻辑:
read first integer from file intInput.dat into positiveIntegerOne
if end-of-file on intInput.dat
display error message “Input file exists but has no values”
read second integer from file intInput.dat into positiveIntegerTwo
if end-of-file on intInput.dat
display error message “Input file has odd number of values”
这是我的尝试:
inFile >> positiveIntegerOne;
if (!(inFile >> positiveIntegerOne)) {
cout << "Input file exists but has no values \n";
return 1;
}
inFile >> positiveIntegerTwo;
if (!(inFile >> positiveIntegerTwo)) {
cout << "Input file has odd number of values \n";
return 1;
}
但是,每当我运行代码时,即使我的文件中确实有一个数字,它也会显示两条错误消息。
您显示的代码尝试读取四个值:
// This reads one value into positiveIntegerOne
inFile >> positiveIntegerOne;
// This reads a second value into positiveIntegerOne
if (!(inFile >> positiveIntegerOne)) {
与相同positiveIntegerTwo
,总共有四个输入。
您需要考虑程序的逻辑:它应该尝试读取第一个值,并且只有在成功之后才应该尝试读取第二个值。
也许是这样的:
if (inFile >> positiveIntegerOne) {
if (inFile >> positiveIntegerTwo) {
// Both values successfully read, do something with them
}
else {
cout << "Could not read the second value\n";
}
}
else {
cout << "Could not read the first value\n";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句