如何在满足条件后终止函数

时间:2013-02-04 00:18:10

标签: c++ c

描述:

我有一个遵循以下格式的文件:number number number,这里有几行:

0 00 19
0 900000 949999
0 9500000 9999999
1 00 09
2 00 19
2 200 349
2 35000 39999
2 900000 949999
2 9500000 9999999
3 00 02
3 7000 8499
3 9500000 9999999
4 00 19
4 7000 8499
80 00 19
80 900000 999999
81 00 19
81 900000 999999
82 990000 999999
83 7000 8499
958 95000 99999
959 7000 8499
960 85000 99999
961 00 19

第一列代表area,第二列代表num1num2

我已设法将每个列存储在其各自的变量中:

int isRegistered(FILE* fp, int area)
{
    int finished = 1;
    int scanned_area;
    char num1[7], num2[7];
    int rc = 1;

    rewind(fp);

    while (finished != EOF) {
        finished = fscanf(fp,"%d %s %s\n", &scanned_area, &num1, &num2);
    }
    return rc;
}

我知道我“不应该使用fscanf”并且不应该使用%s进行扫描,但这些是特定于任务的,我无法更改它们。

现在我将所有这些数字存储在各自的变量中,第一列数字存储在scanned_area中,第二列存储在num1中,第三列存储在num2中。

SCENARIO

我的区域值为1.如何编码,以便在scanning_area == 1时,函数停止?

2 个答案:

答案 0 :(得分:0)

  

我的区域值为1.如何编码,以便在scanning_area == 1时,函数停止?

您可以使用break退出循环:

while (condtion)
{
  // some code
  if (scanned_area == 1)
  {
     break;
  }
}

答案 1 :(得分:0)

如果你想让函数停止然后只返回一个合适的值,在你的情况下返回一个整数。一旦函数命中一个return语句,那么返回该值,并且在执行后没有其他任何内容。

希望这会有所帮助:D