我正在尝试读取此类输入:
[Some text] (x,y)
我需要用整数存储 x,y。
我尝试了以下代码:
#include<iostream>
#include <cstdio>
using namespace std;
int main(){
char temp[20];
int x1, x2;
scanf("%[^(]%d,%d)", temp, &x1, &x2);
printf("%s %d %d", temp,x1,x2);
return 0;
}
但存储在 x1 和 x2 中的整数始终为 0。这是我得到的输出:
this is a trial (8,6)
this is a trial 0 0
错误是什么?
最佳答案
%[^(]%d,%d)
这告诉 scanf()
到:
读取所有不是左(左)括号的字符;
然后读取一个十进制整数,
然后读一个逗号,
然后读取另一个十进制整数,
然后使用尾随的右括号。
缺少的是,在阅读前导文本后,您实际上并没有阅读左括号。因此,要么更改您的格式字符串以包括:
%[^(](%d,%d)
或者,更好的是,考虑手动解析字符串。 scanf()
格式字符串晦涩难懂,很容易犯一个小错误,然后整个事情就大功告成(刚好发生在你身上) .这个怎么样?
char buf[LINE_MAX];
fgets(buf, sizeof(buf), stdin);
const char *lparen = strchr(buf, '(');
const char *comma = strchr(lparen + 1, ',');
// const char *rparen = strchr(comma + 1, ')'); // is this even needed?
char str[lparen - buf + 1];
memcpy(str, buf, lparen - buf);
str[lparen - buf] = 0;
int n1 = strtol(lparen + 1, NULL, 10);
int n2 = strtol(comma + 1, NULL, 10);
关于c++ - scanf 读取格式化输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17115718/