从标准输入中读取C中的特定模式

问题描述 投票:0回答:1

我在使用C的控制台应用程序读取标准输入时遇到麻烦。

我需要以特定的模式/格式(例如'(num,num)')获取输入,且不带引号。那是[[打开parenthesys,一个数字,一个逗号,一个空格,另一个数字,关闭parenthesys]]。

当我用scanf("%d %d", &a, &b);读取程序时,它将读取两个数字,中间用空格隔开。我想尝试使其理解如上所述的所需模式,例如scanf("(%d, %d)", &a, &b);,其中a为第一个数字,b为第二个数字。这在此scanf之后不起作用,我还有另一个输入提示,由于字符串模式而被跳过,但可用于scanf("%d %d", &a, &b);。有什么建议吗?

int main(int argc, char* argv[]) {

  int a, b, c;

  printf(This is where the pait is required: ");
  scanf("(%d, %d)", &a, &b);

  printf("a: %d, b: %d\n", a, b); // Check values here...

  printf("This is where I ask for another number as input: ");
  scanf("%d", &c);

  printf("c: %d\n", c); // Check value here...

  // Do stuff here but above code should skip over the second scanf...

  exit(0);
}
c scanf
1个回答
1
投票

如@dxiv所述“在两个地方都使用" (%d ,%d )"是更安全的,不需要getchar”“还请注意%d'吸收'任何前导空格,因此该格式将读取(123,456),并在数字和定界符之间插入任意数量的空格或换行符。”

© www.soinside.com 2019 - 2024. All rights reserved.