As my title says I’m a new programmer learning C. This is my second day programming and I need help fixing this problem in my code. I’m making a mad lib and while no errors come up the first scanf takes 2 lines rather than the 1 every other scanf uses.
Here’s the code:
#include <stdio.h>
int main()
{
char verb[20];
char loc[20];
char noun1[20];
char noun2[20];
char adj[20];
/* The following is the part where you input words. It sets them as strings (named word1-5, as stated above)*/
printf("Welcome to Mad Libs! \nAnswers can only be one word long. \nPlease enter a verb.\n");
scanf("%s\n",verb);
printf("Now enter a location!\n");
scanf("%s\n",loc);
printf("Now enter a noun!\n");
scanf("%s\n",noun1);
printf("Now enter another noun!\n");
scanf("%s\n",noun2);
printf("Now please enter an adjective!\n");
scanf("%s\n",adj);
/* It all comes together here. The code is supposed to take the strings set previously and put them into this story. */
/* The dashes and various /n's are there to make the final Mad Lib easier to read */
printf("\n\nHere is your Mad Lib:\n------------------------------ \nHolly %s down to the %s.\nOnce she got there she bought some %s and ate it!\nAfterwards, Holly brought it home and let her %s eat it.\nHolly is a %s girl!\n------------------------------ \n",verb,loc,noun1,noun2,adj);
return 0;
}
It was made using a combination of Vi and Sublime Text 2 on Ubuntu.
Like I said, I’m not getting any errors when compiling and everything seems to be in order, the problem is that once I run it in the Terminal I have to enter the first answer (answer to “Welcome to Mad Libs! Answers can only be one word long. Please enter a verb.”) twice and it takes both of them.
Please try running it yourself (it should work in both OS X and Linux as a .c file) if you’re confused as to what I mean, I honestly don’t know how to describe the error very well. It makes me input the first answer twice and causes problems when showing the final mad lib.
Just use
scanf("%s", ...), notscanf("%s\n"). The\ndoesn’t get there until later. (Oh, and this is also a good way to get buffer overflows, by the way, so you might consider usingfgets, et. al.)The way it’s working right now is:
scanfgets the line, but without the\n, so it’s still waiting.scanfnow has the\nat the end of the previous line and uses that string. The first line was read, the second line is now in the buffer, andscanfis awaiting another\nthat already exists.And that has the effect of shifting all of the answers by one.