What am I doing wrong? (C) - c

I really have no idea what I'm doing wrong with this. Every time I compile it, at the fourth user input, it just stops and shows the "processes returned" stuff.
#include <stdio.h>
#include <conio.h>
int main() {
char firstname[15], class, swordch0c1, swordch0c2;
int health, healthtot, armor, armortot;
printf("Hello there! Could I have your first name?\n>");
scanf("%s", firstname);
printf("\n---------------------The Legend of %s---------------------", firstname);
printf("\nPress Enter to continue.");
getch();
printf("\n\n\nYou are %s, a(n): \nA.Swordsman\nB.Assassin\nC.Archer\nD.Mage\n>", firstname);
scanf(" %c", &class);
/*swordsman story starts here*/
if (class=='a' || class=='A')
{
printf("\n\nThere you stand, at your boring everyday post.\nWhen you joined the army, you thought it would be more exciting than this.\nJust then, you see your general walking towards you.");
printf("\n\nYou quickly improve your posture. \"Soldier, I have an opportunity for you\"\nA.\"Really? What is it?\"\nB.\"I'm not interested\"\n>");
scanf(" %c", &swordch0c1);
if (swordch0c1=='b'||swordch0c1=='B')
{
printf("\n\"But... I didn't even tell you what it was. Okay, suit yourself\" You are DOOMED to a life of boredom.\n\n\n\n\n");
}
if (swordch0c1=='a'||swordch0c1=='A')
{
printf("\n\n\n\"Well, you see, there's this dragon. He's been causing big problems.\nHe's destroyed villages, harrassed the priests on the mountain,\n");
...
edit:It does allow me to put in the fourth input. after hitting enter, it shows the processes returned stuff.

This line is almost definitely the problem:
scanf(" %c", &swordch0c1);
You are asking to read a single character, however to actually enter a character you have to type two characters: AEnter. This scanf call will read the 'A', and the next scanf call will read the '\n' (the Enter) key, which is still in the input buffer.
I suggest using fgets() for all user input. It's a lot easier to deal with that way, because it matches the way users actually enter input (line of text plus Enter).

Related

I want to make a time calculator and, there is a need to read a single character, but I tried many way it won't work

this is my program, this is not complete yet but, when I run this program, the single character reading part of it won't read, I checked without adding (&)ampersand. I tried many ways with arrays and so on, but I can't get the result. please help
#include <stdio.h>
#include <stdlib.h>
int main()
{
int F,S,E,SM,EM;
char t1,t2;
//*S=starting time*//
//*SM=start minute*//
//*F=ending time*//
//*FM=end minute*//
printf("\nEnter the start time: Hour : Minute");
scanf("%d %d",&S,&SM);
printf("\nEnter a for AM Enter p for PM");
scanf(" %c",&t1);//problem
printf("\nEnter end time: Hour: Minute");
scanf("%d %d,",&E,&EM);
printf("\nEnter A for AM: Enter P for PM");
scanf(" %c ",&t2);//problem
return 0;
}
}
Scanf() will try to consume ALL the input, which means that the '\n' from pressing enter will carry over to the next scanf call. This is alleviated by you using a leading space character in your format " %c". However, if the format of the input does not exactly match the actual input, i. e. format is "%d %d", but the input is, say " 1 1", scanf() will fail to write the format. I think this is why it's failing for you after compiling and testing out your code.
Consider adding some logging and error checking into this code snippet, so that it's easier to pin down these errors. Even something as simple as printf("%d %d\n", S, SM); after a scanf() call is much better than not tracking your results at all.

What is wrong with my for loop? It turns 2 times when I enter only 1 input in a letter guessing game in C

I know this code is not completed yet, but I cannot go any further because of this issue.
If you execute the code with any compiler you will see it.
After the instructions gets written at console, when you enter a word, loop takes 2 turns. It reduces chance 2 times too when it's supposed to be 1. Why is that?
I am using devc++ and windows.
#include<stdio.h>
#include<stdlib.h>
int main(){
int i,j,totalTrial=6,currentTrial=0;
char myWord [6]={'d','o','c','t','o','r'};
char lineArray [6]={'-','-','-','-','-','-'};
char guess;
printf("Hello,this is a simple word-guessing game. Try to find my secret word. You have 6 chances.");
printf("Lets begin!!\n");
printf("Word:\n------\n");
for(i=0;i<=6;i++)
{
printf("\nGuess a letter: ");
scanf("%c",&guess);
for(j=0;j<7;j++)
{
if(guess==myWord[j])
{
lineArray[j]=guess;
}
}
currentTrial++;
printf("\nResult: %s, %d hakkin kaldi.\n",lineArray,totalTrial-currentTrial);
}
getch();
return 0;
}
This is happening because the scanf() is reading the stray \n (newline character) from the input buffer. [When you are giving input, you must be entering a character followed by ENTER key.]
To resolve this, add a space before % character in scanf() like this:
scanf(" %c", &guess);
This will skip the leading whitespace characters (including newline character) and read the input given by the user.
With regard to the line:
scanf("%c",&guess);
How many characters do you think are turning up when you enter, for example, dENTER? I'll give you a hint, it isn't one :-)
The problem is that your scanf will read each character in turn and process it, including the newline generated when you hit ENTER.
A better solution would be to use a more complete input solution such as this one here.
It will handle many scenarios that a simple method based on scanf or getchar.

Error in C simple program [duplicate]

This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 8 years ago.
This is part of a university lab and the TA tells me there is an error but I haven't a clue. When I run it it asks me for the first char but then runs through the program and doesn't ask me at the second scanf.
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
scanf("%c", &sen);
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
scanf("%c", &ben);
printf("The key just accepted is %d", ben);
}
Actually this is C not C++. Save it as file.c.
Try this:
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
sen = getchar();
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
getchar();
ben = getchar();
printf("The key just accepted is %d", ben);
}
Explanation: when you enter the first character and press enter it takes enter's ASCII code as the second.
I suggest not to use scanf. But it works both ways if you put a getchar to "take" the enter.
Adding a space before %c in the second scanf will solve the issue.
This is done because scanf does not consume the \n character after you enter the first character and leaves it in the stdin.As the Enter key(\n) is also a character,it gets consumed by the next scanf call.The space before the %c will discard all blanks like spaces.
When you are scanning a character(%c) using scanf,add a space before %c as it would help reduce confusion and help you. Therefore, in both the scanfs , you can add the space.
When you pressed your key and then hit enter, you typed in two keys. The first was the desired key ,a for example, and the second was the key <enter> typically written as \n. So, your second scanf captures the result \n.
Since printing out the \n character doesn't result in something that is easy to see on the screen, it will appear like your program is just skipping the second scanf and printing out only the fixed parts of the printf without a easily viewable value.
One way to get around this problem is to consume all the key strokes just before the key you want to capture. This is done by accepting more input after the character up until you see a newline character \n. Once you see that character, then you do your next read.
// flush extra input up the to carriage return
char flush = 0;
while (flush != '\n') {
scanf("%c", &flush);
}
// now read my desired input
scanf("%c", &ben);
that's because nobody accepts '\n'. call scanf like this scanf("%c%*c", &sen). %*c means you want to omit one character, which is '\n'.
btw, void main() is allowed. main function is not the real entry point of executable, so it's ok to do that. but it seems not everybody likes it.

Creating a C face program, but it only takes 2 inputs instead of 3. Why? [duplicate]

This question already has answers here:
C: function skips user input in code
(2 answers)
Closed 8 years ago.
So for a class I am taking I have to learn C and one program I am trying to make is a simple print face program that takes 3 inputted characters and uses them to create a face.
However, whenever I run it, it asks for the eye character, then prints out the "Enter nose character: " but never takes any input, instead skipping right to the mouth character. I have looked over the code and cannot figure out what is causing this.
#include <stdio.h>
void PrintFace(char eye, char nose, char mouth) {
printf("\n %c %c\n", eye, eye); // Eyes
printf(" %c\n", nose); // Nose
printf(" %c%c%c%c%c\n",
mouth, mouth, mouth, mouth, mouth); // Mouth
return;
}
int main() {
char eyeInput;
char noseInput;
char mouthInput;
// Get character for eyes
printf("Enter eye character: ");
scanf("%c", &eyeInput);
// Get character for nose
printf("Enter nose character: ");
scanf("%c", &noseInput);
// Get character for mouth
printf("Enter mouth character: ");
scanf("%c", &mouthInput);
// Print the face using the entered characters
PrintFace(eyeInput, noseInput, mouthInput);
return 0;
}
This is the output I get:
Enter eye character: o
Enter nose character: Enter mouth character: l
o o
lllll
It seems to skip the second scan statement but I can't see why. :/
Because the input stream is line-buffered, you need to press Enter after typing in the character. Now scanf reads a single character from the stream. However, there's still a newline in the stream, and that gets picked up on the next read.
One approach is to use fgets and read a whole line of text, then pick out the first character. However, doing this properly might be a little over the top.
It might be easier if you just use code to ignore characters up until the newline, as suggested here: C code for ignoring the enter key after input. Also, you should consider using getchar or getc instead of scanf. Just make a simple function to do all this stuff, and call it whenever you want to read a character.
The carriage return you're passing by hitting "Enter" after your first character is considered a second character input. Notice the difference in carriage returns in your output.
See the linked question at: C: function skips user input in code
If I remember well, scanf does not take '\n' in a string. So you put for example "dog" as a first entry but you type an enter at the end. So the second scanf take that '\n' in the buffer shiting your program. Solution? Clean up your buffer. If you are over windows fflush() can save you, using fflush(stdin) after each scanf. Over unix fflush() does not work like that and you have to do it manually. An easy way is to put a getc() or something like that that consumes that '\n'

How can I make scanf() with multiple inputs ignore the others?

scanf("%s %d %s %d",word1,&num1,word2,&num2);
so when the user inputs "quit", its supposed to stop asking for the other 3 inputs. however it asks me to input another "quit" probably because there are 2 %s in the format
is there anyway around this?
EDIT: because it has to get 4 inputs in a loop, unless a quit is inputted.
scanf is a very blunt tool that is not good at talking to unstructured inputs (including humans :-) ). In general, if you are interacting with a person, you should start with fgets to read a line, then pick the resulting line apart however is most convenient, possibly including sscanf.
It's worse than you think because the %d directive will jam up if you feed it something that is not scan-able as an integer. For instance, if you enter quit now, the first %s directive will read the word quit but the %d will leave now in the input stream, causing scanf to return 1 (one successful conversion-and-assignment). The next attempt to read a string will obtain and consume the now; to naive code, this will seem like it was a later, second input line, rather than a continuation of the first one.
#include <stdio.h>
#include <string.h>
scanf("%s ", word1);
if (strcmp(word1, "quit") != 0)
scanf("%d %s %d", &num1, word2, &num2);

Resources