Hangman
I'm using scanf to get a character entered by the user (guessed letter), but it seems like scanf gets all the letters entered
char guessed_letter;
printf("\n");
scanf(" %c", &guessed_letter);
enter image description here
if the word is moon
if the user entered moo
this happens
m _ _ _
m o _ _
m o o _
but what I'm expecting is to read only the first one.
m _ _ _
this problem aslo occures when counting mistakes because it scans more than one charachter
I'm scanning for the letter in a do while loop, because I want the user to keep guessing
this code will work for you. first of all you take the whole word from the user. because the users want to write whole word not a just character. (by the way if you don't want to deal with the "malloc", you can use the strdup. but i suggest learn to the malloc.) The first letter of the character from the user is the value you want. you can write it by its first index (guessed_letter[0]).
#include <stdio.h>
#include <string.h>
int main()
{
char *guessed_letter = strdup("");
printf("\n");
scanf("%s", guessed_letter);
printf("first character is: %c", guessed_letter[0]);
}
Related
I've written a small program to practice getting user input using getchar() and outputting it using putchar() in C.
What I want my program to do:
I want the program to ask the user to enter a char, store it in a char variable, and print it out. And then I want it to ask the user to enter another char, store it in another char variable, and print it out.
The following is my code:
#include <stdio.h>
int main()
{
printf("Please enter a char: ");
char myChar = getchar();
printf("The char entered is: ");
putchar(myChar);
printf("\n");
printf("Please enter another char: ");
char myChar2 = getchar();
printf("The char entered is: ");
putchar(myChar2);
printf("\n");
return 0;
}
When I run this program in my Terminal, the following is what I see, which is not how I expect it to behave.
cnewbie#cnewbies-MacBook-Pro c % ./a.out
Please enter a char: k
The char entered is: k
Please enter another char: The char entered is:
cnewbie#cnewbies-MacBook-Pro c %
When I run the program, it outputs "Please enter a char: " and waits for me to enter a char. I type k and hit return. Then it outputs not only "The car entered is: k" but also the other lines shown above all at once.
Question: Why doesn't my program wait for me to input another char?
I'm a beginner in C and I have no clue why this is behaving this way. Please help!!
getchar also reads white space characters including the new line character '\n' that is placed in the input buffer due to pressing the Enter key.
Instead use a call of scanf the following way
char myChar;
scanf( " %c", &myChar );
^^^^
Pay attention to the leading space in the format string. It allows to skip white space characters.
The Spinx brothers have planted a bomb in Tokyo’s Metropolitan Police Headquarters. Quite
conveniently, they left behind a string S (encrypted, of course) as the key to defuse the bomb, but
there is more to it.
The police from their previous encounters with the Sphinx brothers have deduced a possible
decryption. Some of the letters in the string need to be replaced with some other letter in accordance
with the decryption pattern. It is possible that a decrypted letter can be decrypted/replaced again.
You need to replace each letter in the string until it cannot further be replaced, to obtain the key.
They challenge you to do this as quickly as possible, as the bomb in the headquarters is about to
explode any time now.
Input
The first line has the string S (1 ≤ |S| ≤ 105) consisting of lowercase letters only. The next line has a
single integer M (1 ≤ M ≤ 325), denoting the number of replacements. The next M lines have two
spaced characters, ci and di, with di being the replacement of ci.
Output
Print the final string after all character replacements.
Note
It is guaranteed that there are no cyclic replacements.
input
nineandeleven
5
n l
l u
u w
e a
a y
output
wiwyywdywyvyw
This is how I coded it. I couldn't take more than 3 rows of inputs
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
char str[100000];
scanf("%s",str);
int M;
char x,y;
scanf("%d",&M);
for(int i=0;i<M;i++){
scanf("%c %c",&x,&y);
for(int j=0;j<strlen(str);j++){
if(str[j] == x) { str[j]=y;}
}
}
printf("%s",str);
return 0;
}
scanf("%c %c",&x,&y);
change to
scanf(" %c %c",&x,&y);
one more space
because when you enter "enter"
will push newline(windows.linux may be little different like \t\n \n if you want to know google it) to your buffer
when you use %c will read last you push not jump space, '\n', '\t'
when you add space in front of %c
scanf will jump space, '\n', '\t' before read buffer then will get correct your input by your keyboard
maybe its a bug i didnt it like that before seems you increment the index in the first %c scanf
there is a solution u can use strtok(str, delimiter) in string.h each time scan the whole string like "l p" then split it with the white spase
char d[3];
scanf("%s", d);
x = s[0];
y = s[2];
then increment your index etc..
or split it
char *token;
char d[3];
scanf("%s", d);
token = strtok(d, ' ');
x = token[0];
y = token[1];
Good Luck
I am trying to create a program that compares the letter a user inputs to my letter. If the letters are the same, the program should say that they are the same, then terminate. If they are not the same, then the user should be prompted to enter another character until they guess it correctly.
I have tried nesting an if statement and nesting a while loop to achieve the case where the letters are equal.
#include <stdio.h>
int main()
{
char myLetter = 'a';
printf("insert a char:");
char userLetter;
scanf("%1s", &userLetter);
while (userLetter != myLetter)
{
printf("%c does not match mine, try again:", userLetter);
scanf("%1s", &userLetter);
}
while (userLetter == myLetter)
{
printf("char matches! program will terminate now. ");
break;
}
}
expected:
insert a char:h
h does not match mine, try again:j
j does not match mine, try again:g
g does not match mine, try again:f
f does not match mine, try again:a
char matches! program will terminate now.
actual:
insert a char:h
h does not match mine, try again:j
j does not match mine, try again:g
g does not match mine, try again:f
f does not match mine, try again:a
a does not match mine, try again:a does not match mine, try again:^C
The proper format operator for reading a single character is %c, not %1s. The latter reads a single character, but writes it into a null-terminated string, so it will write a null byte outside the userLetter variable, which causes undefined behavior.
You should put a space before the operator to make scanf skip over whitespace before reading the character. This is needed to make it ignore the newline after each response.
You should also turn off output buffering or flush the buffer after each prompt, since they don't end with a newline.
There's no need for the while loop at the end, since you don't get out of the first loop until the characters match.
This is a working version:
#include <stdio.h>
int main()
{
char myLetter = 'a';
setbuf(stdout, NULL);
printf("insert a char:");
char userLetter;
scanf(" %c", &userLetter);
while (userLetter != myLetter)
{
printf("%c does not match mine, try again:", userLetter);
scanf(" %c", &userLetter);
}
printf("char matches! program will terminate now.\n");
}
If you are comparing 2 char why don't you get user letter with scanf("%c", userLetter) and then you can compare them with = or != operator. If you are getting input expecting a string value, then I suggest you to declare userLetter like this:
char* userLetter[1];
and then use scanf the way you did in your code BUT you have to compare the strings with strcmp function.
#include <stdio.h>
main()
{
int num;
char another="y";
for(;another=="y";)
{
printf("no. is ");
scanf("%d", &num);
printf("sq. of %d is %d", num,num*num);
printf("\nWant to enter another no. : y/n");
scanf("%c", &another);
}
}
I have C code like this. According to me, this should work like: Enter the no and give square. But its nor running in infinite loop. But it is running only once. Why?
I am using GCC4.8.1 compiler on windows 64 bit.
Because on second iteration scanf assign \n to anotherinstead of assigning y.
EXPLANATION: When you press Enter key after typing the input, then one more character goes to the buffer along with the typed input. This character is produced by Enter and is \n. Suppose you typed y and then pressed the Enter key then the buffer would contain y\n, i.e, two characters, y and \n.
When scanf("%d", &num); is executed then it reads the number typed in and leaves behind the \n character in the buffer for next call of scanf. This \n is read by the next scanf call scanf("%c", &another); irrespective of what you have typed in your console.
To eat up this new line char, use a space before %c specifier in scanf.
scanf(" %c", &another);
^Notice the space before %c.
And change
for(;another=="y";) {...} // Remove the double quote.
to
for(;another=='y';) {...} // Single quote is used for `char`s.
The test in the loop is wrong:
another=="y"
this compares the value of another, a single character, with the value of a string literal, which will be reprented as a pointer to the character y. It should be:
another == 'y'
You should have gotten compiler warnings for this, since it's very strange to compare a small integer with a pointer.
#include<stdio.h>
int main()
{
char a, b;
scanf("%c", &a);
scanf("%c", &b);
printf("%c %c",a,b);
return 0;
}
When I run this program, I only get output as a & I don't get the prompt to enter 2nd character. Why?
In this line,
scanf("%c", &a);
you are actually taking a %d from the stdin (standard input) but at the time you entered a character from stdin, you also typed ENTER from your keyboard which means that now you have two characters in stdin; the character itself & \n. So, the program took first character as the one you entered & second character as \n.
You need to use
scanf("%c\n", &a);
so that scanf eats the newline (that came by pressing ENTER) too.
As rodrigo suggested, you can use these too.
scanf(" %c", &a); or scanf("%c ", &a);
The way you are thinking that second character is printed is wrong. It's actually being printed but it's \n so your prompt might be coming to the next line.
Your code will work if you enter both characters without using ENTER.
shadyabhi#archlinux /tmp $ ./a.out
qw
q wshadyabhi#archlinux /tmp $
Note, when you used this, the only thing in STDIN was q & w. So, the first scanf ate q & the second one w.
Because when you press the enter key, the resulting newline is read as a separate character into b. Try this instead:
#include<stdio.h>
int main()
{
char a, b;
scanf("%c %c", &a, &b);
printf("%c %c",a,b);
return 0;
}
The %c is a format string which accepts only a single character. I think you pressed Enter key as soon as you pressed an alphabet key. The Enter key is also recognized as a character. So the next variable is taking the enter key which has a value of "\0".
The computer is still printing the character from the second variable but its invisible since nothing is getting printed. If you keenly observe, there will be a new line.
Enter two characters one after the other and you will be getting the right output.