我的代码有什么问题吗? 当给出以下输入时(通过文件):
6.02
110 223 144 208 199.5 890
200 69.5 300 138.7 190 601
它会打印ERROR: invalid Price in Airlines # 1
,但它不应该这样做。
这是我的代码。
int fillPricesTable(double flightsPrices[][DEST],int n,double* dollarRate)
{
//n is the number of rows
double Price;
int AirLinesCounter=0;
while (scanf("%lf",dollarRate)==EOF || *dollarRate<=0)
{
errorDollar();
fflush(stdin);
}
for (int i=0;i<n;++i)
{
for (int j=0;j<6;++j)
{
if (scanf("%lf",&Price)==EOF || Price<=0)
{
printf("ERROR: invalid price in airline # %d\n", i);
return -1;
}
flightsPrices[i][j]=Price;
}
AirLinesCounter++;
if(scanf("%lf",&Price)==EOF)
break;
}
return AirLinesCounter;
}
最佳答案
因为if(scanf("%lf",&Price)==EOF)
for (int j=0;j<6;++j)
正文之后循环( AirLinesCounter++
之后的那个),您在 i
上的每个循环中扫描过多的一个数字.
只需删除第二个 if
与 body 。
fflush(stdin);
技术上是未定义的行为。要从输入读取缓冲数据,请循环 getchar()
直到换行符或 EOF。
例如,您可以删除第二个 if,并在错误中添加一个条件来处理单独扫描行中第一个数字的错误:
int fillPricesTable(double flightsPrices[][DEST], int n, double *dollarRate)
{
while (scanf("%lf", dollarRate) != 1 || *dollarRate <= 0) {
errorDollar();
for (int i; (i = getchar()) != '\n' && i != EOF;);
}
bool end_me = false;
int i = 0;
for (i = 0; i < n && end_me == false; ++i) {
for (int j = 0; j < 6; ++j) {
// no need to scan into temporary variable
// just scan into the destination
if (scanf("%lf", &flightsPrices[i][j]) != 1 || flightsPrices[i][j] <= 0) {
if (j == 0) {
// this is first number in the row
end_me = true; // using separate variable to end the outer loop
// because C does not have "break 2" or similar.
break;
} else {
errorPrice(i);
return -1;
}
}
}
}
return i; // AirLinesCounter is equal to i....
}
关于c - Scanf 意外返回 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59564899/