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:
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
scanfto:Note the space before the
{.