r/cprogramming • u/Eliminator152 • Jan 20 '24
Why doesn't my code work?
I am brand new to this, I'm just starting with like no experience. I know this is going to seem a bit childish, but this is the code I'm working on. I thought it'd be hilarious if I made something that resembled a chatbot since so far I've learned the printf and scanf functions, as well as variables in my programming class. I saw online that using %[^\n]s causes scanf to read the user input up to the next line and store it in the variable I set. Problem is, it works fine for the first input, then prints the rest of the text without prompting another user input. Any ideas what I need to change in this code? (also apologies if I formatted this post wrong, I'm not familiar with this sub)
#include<stdio.h>
int main()
{
char ans1\[100\];
char ans2\[100\];
char ans3\[100\];
setbuf(stdout,NULL);
printf("Hello! I am ChatECK!\\nWhat is your name? ");
scanf("%\[\^\\n\]s", ans1);
printf("LMAO %s DEEZ NUTS!\\n", ans1);
printf("Ask me anything! ");
scanf("%\[\^\\n\]s", ans2);
printf("%s DEEZ NUTS!\\n", ans2);
printf("Tell me something about yourself: ");
scanf("%\[\^\\n\]s", ans3);
printf("%s DEEZ NUTS LOL!\\n", ans3);
printf("Thanks for chatting with me!");
return 0;}
The output ends up with this after I enter my name:
Hello! I am ChatECK!
What is your name? Eliminator152
LMAO Eliminator152 DEEZ NUTS!
Ask me anything! ��a DEEZ NUTS!
Tell me something about yourself: DEEZ NUTS LOL!
Thanks for chatting with me!
1
u/aghast_nj Jan 20 '24
When you answered, you typed "Eliminator152" and then you hit return.
The problem is, that created an input file like
0000: 45 6c 69 6d 69 6e 61 74 6f 72 31 35 32 0a Eliminator152.And your scanf("%[^\n]s", ...) reads in any character other than a newline, over and over again:
0000: 45 6c 69 6d 69 6e 61 74 6f 72 31 35 32 0a Eliminator152.
^-- Is it [^\n]? take it!
^-- Is it [^\n]? take it!
^-- Is it [^\n]? take it!
^-- Is it [^\n]? take it!
...
Is it [^\n]? Whoa, hold up! --^Until it sees a newline. Then it stops copying, and tried to match the next character in your format string: s.
You wrote "%[^\n]s" probably meaning "take this character class as a restriction of the %s conversion specifier."
But that's not how it works. To scanf, square brackets are a conversion specifier. You don't need to add the 's'.
Also, did you notice that scanf didn't take your newline? When you printed the result, did you see the newline from your \n in the printf format string? Did you see an extra newline in there? No. Because you told scanf not to accept any newlines. So when scanf finished reading the first time, the input file was still:
0013: 0aSo you said, scanf("%[^\n]s", ans2)
And scanf said: "Sorry, boss, the first input character is a newline. Peace, out!"
And your ans2 variable (along with all the others) is on the stack, so it's full of random garbage left over from when you were watching those videos you like. >:-| And so that got printed out.
There are a lot of problems with using scanf, and this is one of them. The solution to your particular problem is "eat the whitespace." In fact, that's the solution to like 30% of all scanf problems.
The Choice is Yours
In C, newlines are considered white space characters just like space and tab (and others). So you can rely on the whitespace matching behavior of scanf to skip/consume the newlines.
You can get with this
You might choose to consume spaces at the beginning of the format string. This will, of course, consume any spaces the user types in:
scanf(" %[^\n]", ans)The nice thing about this approach is that it can become a habit, and it clears out any leftover newlines or other whitespace in the input file.
Or you can get with that
You might choose to consume spaces at the end of your format string. After all, the newline is at the end of the input, so why not match it explicitly?
scanf("%[^\n] ", ans)You might even use the newline character, as a reminder of what you are consuming:
scanf("%[^\n]\n", ans)You can put spaces in there, too -scanf matches all white space whenever it sees any single space character in the format string:
scanf("%[^\n] \n", ans)¿Por qué no los dos?
When you're programming in C, the question is not, "Am I paranoid?"
When you're programming in C, the question has to be, "Am I paranoid enough?"
So you might consider putting in the space at the front to take care of any problems accidentally left over, and the space (or newline) at the back to pick up the actual newline you are expecting to see:
scanf(" %[^\n] \n", ans)Interestingly, it makes the format a bit easier to read, as well.
Did you know ...
Here's something you may not know: C has a feature that is aimed at solving the "terminal wrap-around" problem that allows splitting string literals.
That is, you can have two literals right next to each other, and the compiler will automatically concatenate them:
"Hello," " world"In fact, today only, special price, you can use more than two literals next to each other. It'll concatenate them all! Now how much would you pay?
Why am I telling you this? Because you can #define a literal (once you have it working) and use nice names to put your format strings together:
#define EAT_WS " "
#define ENTIRE_LINE "%[^\n]"
#define INT "%d"Note that these are all literals, they still have their quotes. But:
scanf(EAT_WS ENTIRE_LINE EAT_WS, ans)
scanf(EAT_WS INT "/" INT "/" INT EAT_WS, &yy, &mm, &dd)You might even want to use the variadic macro feature of C99:
#define my_scanf(fmt, ...) \
\
scanf(" " fmt "\n", __VA_ARGS__)(Note that this will fail for a scanf with no arguments. But who does that?)
4
u/SahuaginDeluge Jan 20 '24 edited Jan 20 '24
I'm not a C expert, but...
First, there are a lot of extra
\symbols in your posted code (I think this is Reddit editor since it almost happened to me too).After that, from what I read, the
scanfformat you're using should be:scanf(" %[^\n]", ans1);without the 's' but with a starting space. I'm not sure exactly what this is doing but I confirmed it works.
But, also from what I read, it is recommended I think to use
fgetsoverscanf.The line to read into
ans1withfgetswould look like this:fgets(ans1, sizeof ans1, stdin);This has the issue that it will include the
\nin the resulting string which you may not want. You can apparently remove it like this:ans1[strcspn(ans1, "\n")] = '\0';Resulting program looks like this:
See also:
https://stackoverflow.com/questions/43174201/alternative-to-gets
https://stackoverflow.com/questions/17294809/reading-a-line-using-scanf-not-good
https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input
https://en.cppreference.com/w/c/io/fgets