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!
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