开发者

Lookahead in C/Reading

开发者 https://www.devze.com 2023-04-06 14:02 出处:网络
I wrote this code, as a sort of lookahead. int main() { char a[100]; char b[100]; scanf(\"%s\", a);开发者_开发百科

I wrote this code, as a sort of lookahead.

int main() {
    char a[100];
    char b[100];
    scanf("%s", a);开发者_开发百科
    if (a[0] == '@') {
        scanf("{%s}", b);
    }
    printf("%s\n", b);
}

For some reason, I get a segfault after hitting enter the first time, my input was @hi. What's going on?


The problem in your first piece of code (before the edit) was that you were creating a string storing 2 characters. The '0' and the NULL. You then try to overwrite this with 4 characters from scanf.

In the second piece of code, you're not pointing the char pointer anywhere. You just declared it without giving it a value so it could be pointing to anything.

To get the behaviour you want you need to create an array of chars like this:

char a[100];
char b[100];

You'll have to make the array big enough for your purposes.

Also, if you want to read the two strings in, you'll have to "consume" the white space between them. To do this, change the second scanf to:

scanf(" {%s}", b);

Note the space before the {.


scanf("%s", a);, per the man page, tries to store a string (%s) in the locations pointed to by the pointer arguments that follow format (a). In this case, a is uninitialized and does not point to any storage space. To read a single character, consider this example:

int main(int argc, char **argv)
{
    char c;


    /* among other things, read a character */
    scanf("%c", &c);

    return 0;
}

expand on it to get the intended behaviour. Additionally, I would advise you to steer clear of scanf, and do your matching yourself while reading with fgets.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号