首页 > 解决方案 > 如何从这种输入格式中提取数字?

问题描述

我需要像我突出显示的行一样“扫描”。我如何提取数字?我在课程的开始,所以不要发布我可能还没有研究过的过于复杂的解决方案。

输入(房屋成本、首付、储蓄、储蓄年率、抵押年率、工资、部分储蓄、年薪、房租):

(600000, 0.15, 50000, 0.02, 0.03, 10000, 0.3, 0.03, 2000)

C 语言。

标签: cinput

解决方案


我如何提取数字?

简单的方法是读取该行,fgets()然后解析sscanf()"%n"记录扫描的偏移量,如果它到达那么远。

使用允许(,)分隔符附近有空格的格式。
"%lf"已经消耗了领先的空白。

  #define EXPECTED_SIZE 100
  char buffer[EXPECTED_SIZE * 2];  // Be generous in buffer size

  // Was a line successfully read?
  if (fgets(buffer, sizeof buffer, stdin)) {

    // Example code simplified to 3 variables
    double House_cost, down_payment, savings;
    int n = 0;
    sscanf(buffer, " (%lf ,%lf ,%lf ) %n",
        &House_cost, &down_payment, &savings, &n);
    // Did scanning reach the %n and was that the end of the line?
    if (n > 0 && buffer[n] == '\0') {
      Success();
    } else {
      Failed();
    }
  }

一个好的解析器已经准备好检测错误的输入。不要假设输入格式正确。


推荐阅读