解析数据,scanf?

Parsing data, scanf?

我是编程新手,我想以如下格式解析数据:

4 ((182, 207), (385, 153), (638, 639), (692, 591))

第一个数字表示将出现的对数。我想将每对的第一个数字保存为 X 轴,将每对的第二个数字保存为 Y 轴。 在我的脑海里,我现在想通过 scanf 保存整行,然后尝试解决括号和逗号的数量,但我不确定这是否是正确的方法或如何正确实施它。我不想使用任何内置容器或字符串。我试图通过 scanf 做类似

for(int i= 0; i < pair_count;i++){
scanf("(%d, %d)",tabx[i],taby[i])

}

但它不起作用:(。我不知道如何正确格式化 scanf 我猜或者我的想法是完全错误的。

scanf() 需要变量的地址,而不是变量本身。所以尝试:

   scanf("(%d, %d)",&tabx[i],&taby[i]); 

你也可以尝试使用c++流:

  for(int i= 0; i < pair_count;i++){
      char d1,d2,d3;
      if ( (cin >> d1 >> tabx[i] >> d2 >> taby[i] >> d3) && d1=='(' && d3==')' && d2==',') {
         ... //process data
       }
       else cout << "Wrong input !"<<endl;
  }

您必须输入所有匹配的字符。这有点棘手,因为 , 在最后一对数字之后不存在。

以下示例代码可以解决您的问题。

#include <cstdio>
#include <cstdlib>

int main() {
    // 4 ((182, 207), (385, 153), (638, 639), (692, 591))

    int pair_count;
    scanf("%d", &pair_count);
    scanf(" (");

    int* tabx = new int[pair_count];
    int* taby = new int[pair_count];
    for (int i = 0; i < pair_count-1; ++i) {
        if (scanf("(%d, %d), ", &tabx[i], &taby[i]) < 2) {
            fprintf(stderr, "Input error!\n");
            return EXIT_FAILURE;
        }
    }
    if (scanf("(%d, %d))", &tabx[pair_count-1], &taby[pair_count-1]) < 2) {
        fprintf(stderr, "Input error!\n");
        return EXIT_FAILURE;
    }

    for (int i = 0; i < pair_count; ++i) {
        printf("%d %d\n", tabx[i], taby[i]);
    }

    delete[] tabx;
    delete[] taby;
}

或者,您可以读取整个字符串输入并将所有 (), 替换为 (space).之后,您可以简单地解析数字。另一方面,这消除了数据格式的验证。