简体   繁体   English

scanf读取格式化的输入

[英]scanf reading formatted input

I am trying to reading an input of the sort: 我正在尝试阅读这种输入:

[Some text] (x,y)

where i need to store x,y in integers. 我需要以整数存储x,y。

I tried this following code: 我尝试了以下代码:

#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;
}

But the integers stored in x1 and x2 are always 0. This is the output i get: 但是存储在x1和x2中的整数始终为0。这是我得到的输出:

this is a trial (8,6)
this is a trial  0 0

What is the error? 有什么错误?

%[^(]%d,%d)

this tells scanf() to: 这告诉scanf()可以:

  1. Read all characters which aren't a left (opening) parenthesis; 读取所有非左括号的字符;

  2. Then read a decimal integer, 然后读取一个十进制整数,

  3. then read a comma, 然后读一个逗号,

  4. then read another decimal integer, 然后读取另一个十进制整数

  5. then consume the trailing closing parenthesis. 然后使用结尾的右括号。

What's missing is that after reading the leading text, you don't actually read the opening paren. 缺少的是,在阅读开头的文字之后,您实际上没有阅读开头的内容。 So, either change your format string to include that: 因此,可以更改格式字符串以包括以下内容:

%[^(](%d,%d)

Or, even better, consider parsing the string manually. 或者,甚至更好的做法是,考虑手动解析字符串。 scanf() format strings are obscure and it's easy to make one slight mistake and then the entire thing goes boom ( as just happened to you ). scanf()格式的字符串比较晦涩 ,很容易犯一个小错误,然后整个事情就发起来了( 就像您刚发生的一样 )。 How about this instead? 怎么样呢?

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);

Some demo for goodness sake... 为了演示而进行的演示...

You forgot a paren ( : 您忘记了括号(

scanf("%[^(](%d,%d)", ...);
//          ^

After reading the not- ( s you want to consume one before reading the int s. 读完非符号(之后,您要在读int之前消耗一个。

EDIT as H2CO3 kindly mentioned: use fgets and strchr or sscanf , they are much safer 编辑为H2CO3友好地提到:使用fgetsstrchrsscanf ,它们更加安全

Because of the ( issue is occurring. You need to skip that character. 由于发生了(问题。您需要跳过该字符。

Use: scanf("%[^(](%d,%d)", temp, &x1, &x2); 使用: scanf("%[^(](%d,%d)", temp, &x1, &x2);

"%[^(]%d,%d)" ---> "%[^(](%d,%d)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM