Input problems scanf()/getchar() - c

I am making a text based game, and i am having a big problem with input. Here is a small example of my problem code.
#include <stdio.h>
#include <stdlib.h>
char c;
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
c = getchar();
printf("\nYour input: %c\n", c);
sleep(1);
system("clear");
}
return 0;
}
So, if you compile/run this, and type in 'abc', it will just take each one, and send it through the loop. What I need it to do is only take the very first character that someone types in, no matter how many they do type in.
And, PS: I have tried it this way, and it does the same thing:
#include <stdio.h>
#include <stdlib.h>
char c[2];
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
scanf("%1s", c);
printf("\nYour input: %c\n", c[0]);
sleep(1);
system("clear");
}
return 0;
}
EDIT: It also adds a space to what ever you type in, I assume it is a \0, but im not sure. Thanks!

When you use scanf, enter a string and hit the ENTER key, a string and a character are placed in the input buffer, they are namely: the entered string and the newline character. The string or character by character gets consumed by the scanf but the newline remains in the input buffer, unless you consume that too.
getchar(), on the other hand will not wait for ENTER key, it would read character by character, then your logic.

I think you can add 1 more line to read all the characters that come after the first one until there is a newline character (i.e. the user presses Enter):
while (getchar() != '\n');
Adding to your example, it would be like this:
#include <stdio.h>
#include <stdlib.h>
char c;
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
c = getchar();
printf("\nYour input: %c\n", c);
sleep(1);
system("clear");
while (getchar() != '\n');
}
return 0;
}

Use getch() which does not wait for a newline.

What i think you look for is something like this code, to save very first character, you can also check if c == '\n' to continue your operation, but i dont know what you want after saving very first character:
int i,c;
char save;
for ( i = 0;(c=getchar())!= EOF ; i++)
{
if ( i == 0)
save = c;
}

You can use fgets(), and extract its first character, like...
char ch[2], c;
fgets(ch, 2, stdin);
c = ch[0];

Related

Why gets(sen) is not working in this code?

#include <stdio.h>
#include <string.h>
int main() {
char a;
char s[100];
char sen[100];
scanf("%c",&a); // take character
printf("%c",a); //print character
scanf("%s",s); //take input as a word
printf("\n%s",s); //print the word
if((gets(sen))=='\n')
gets(sen);// take input as a string
puts(sen); //print that string
}
As gets() takes input from buffer so it will take '\n' as input after that another gets() command should work but that is not working. It doesn't take any input. Why?
gets(sen) returns sen, which is the address of the char array.
Therefore, what you are trying to do should be
if(strcmp(gets(sen), "\n") == 0)
gets(sen);// take input as a string
However, this is error-prone because sen can be a space with a newline, which is not "\n" or so.

C: Scanning While not EOF Loop Unexpected Results

I know there are many questions on the same topic of scanf until EOF is reached, but here's a particular case I haven't seen. Suppose I want to make a C program where the user enters a single character, and the program prints back the character and the number of times the user has entered a character until they press CTRL+D (EOF)
This is what I have:
#include <stdio.h>
int main(){
char thing;
int i=0;
while(scanf("%c", &thing) != EOF){
printf("time:%d, char:%c\n",i,thing);
i++;
}
return 0;
}
However, the output is not as expected. It's the following:
f
time:0, char:f
time:1, char:
p
time:2, char:p
time:3, char:
m
time:4, char:m
time:5, char:
I'm not too sure why i is being incremented again, and why printf gets executed again. Perhaps I'm missing something.
Try
#include <stdio.h>
int main(){
char thing;
int i=0;
while(scanf("%c", &thing) != EOF){
if (thing!='\n') {
printf("time:%d, char:%c\n",i,thing);
i++;
}
}
return 0;
}
#user2965071
char ch;
scanf("%c",&ch);
With such a snippet one reads any ASCII character from the stream including new line, return, tab, or escape. Thus, inside the loop I would test the symbol read with one of the ctype-functions.
Something like this:
#include <stdio.h>
#include <ctype.h>
int main(){
char thing;
int i=0;
while(1 == scanf("%c", &thing)){
if (isalnum(thing)) {
printf("time:%d, char:%c\n",i,thing);
i++;
}
}
return 0;
}
As for me, I think it's not a good idea to check scanf for returning EOF. I would rather check for the number of good read arguments.

how to read a char value in C without going to next line

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char p,q;
printf("Hello enter char: ");
p=getchar();
printf("the char is: %c\n",p);
printf("Hello enter char: ");
q=getchar();
printf("the char is: %c\n",q);
return 0;
}
(WHY IS MY OUTPUT for the second printf and scanf not waiting for me to input a char before exiting the program?.....what i mean is u know where it says q=getchar();??? shouldnt it wait for to input a char before exiting the program? but for some reason the program just exits when it goes to the next line...
when pressing enter,a character '\n' is inputing.So your getchar() was used before you enter the second character.I think you want the code below:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char p,q;
printf("Hello enter char: ");
p=getchar();
printf("the char is: %c\n",p);
int c;
while((c = getchar()) != '\n' && c != EOF && c != ' ') ;
printf("Hello enter char: ");
q=getchar();
printf("the char is: %c\n",q);
return 0;
}
You can also use a getch() instead of getchar() to avoid pressing enter key.
#include <stdio.h>
#include <conio.h>
int main(void)
{
char p,q;
printf("Hello enter char: ");
p=getch();
printf("the char is: %c\n",p);
printf("Hello enter char: ");
q=getch();
printf("the char is: %c\n",q);
return 0;
}
When encountering invalid user inputs, use getchar() to read char, and other similar instances where there are undesired characters stuck at input stream(like in your case it was a newline) I define a constant named FLUSH
#define FLUSH while(getchar() != '\n')
to solve the problem. What this statement does is that it reads a character and then throws it away. Now if you try to place it after one of your getchars i.e.
p=getchar();
printf("the char is: %c\n",p);
FLUSH;
it will read the newline then stops because the condition within the while statement no longer holds.
Note: Using getchar() for prompts leaves a '\n' in the input stream you will find this troublesome once you make another prompt and have not eradicated that '\n'.

C - Scan chars and show ASCII code

This is a super basic question... I am relearning C (haven't used it for more than 5 years). I can't get this code to work. I am trying to scan a user input (ascii character) as an integer, and show the ascii code for the entered character.
#include <stdio.h>
int main(int argc, char *argv[]) {
int character;
printf("Welcome to ASCII:\n");
do {
scanf("%d",&character);
printf("ascii: %d\n",character);
} while(character != 999);
printf("Done.\n");
return 0;
}
It just shows 0 for every input...
" I am trying to scan a user input (ascii character) as an integer, and show the ascii code for the entered character"
What you should do is exact opposite. You should read a character and display it as an integer, i.e.:
char c;
scanf("%c", &c); // <-- read character
printf("%d", c); // <-- display its integral value
input: a, output: 97
Also note that while(character != 999) isn't very lucky choice for a terminating condition of your loop. Checking the return value of scanf to determine whether the reading of character was successful might be more reasonable here:
while (scanf("%c", &character)) {
printf("ascii: %d\n", character);
}
try this:
#include <stdio.h>
int main(int argc, char *argv[]) {
char character;
printf("Welcome to ASCII:\n");
do {
scanf("%c",&character);
getchar(); // to get rid of enter after input
printf("ascii: %d\n",character);
} while(character != 999);
printf("Done.\n");
return 0;
}
output:
d
ascii: 100
s
ascii: 115
You are trying to read an integer(scanf("%d", &...)) and it's normal this operation to fail and the value to be 0 - a default value for int variable. Change the "%d" to "%c" and it should work.
change to :
printf("ascii: %c\n",character);
However , What your condition speciftied 999?

C delete chars from string

I have program that asks to enter a string (mystring) and a char (ch). Then it deletes all entered chars (ch) from the string (mystring). For example "abcabc" and char 'a' then the result shoud be "bcbc".
-When I use scanf the program works nicely if the string does not have spaces. If I enter "abc abc abc" It reads and processes only the first 3 letters (until space).
Then I was advised to use gets(mystr); because it can read all the stirng. But when I use gets the result is the same as the input string and nothing happens.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
int main(int argc, char *argv[])
{
char mystr[N] ,result[N];
char ch;
int i,k;
k=0;
printf("enter string \n");
//gets(mystr);///////////////////////////
//scanf("%s",&mystr);///////////////////
printf("enter char \n");
scanf("%c",&ch);
scanf("%c",&ch);
for ( i = 0; i <= strlen(mystr); i++ )
{
if (mystr[i] != ch)
{
result[k]=mystr[i];
k++;
}
}
puts(result);
system("pause");
return 0;
}
scanf("%c",&ch);
scanf("%c",&ch);
That second scanf is your problem. It's picking up the new-line character that you enter after the letter you want to remove (and overwrites the previous value of ch).
Get rid of it.
Please note, as the man page says:
Never use gets(). Because it is impossible to tell without knowing the data in advance how many
characters gets() will read, and because gets() will continue to store characters past the end of
the buffer, it is extremely dangerous to use. It has been used to break computer security. Use
fgets() instead.
hmm - not sure what the problem is - use getstr, but not scanf for the string, and it works for me in visual studio
int main(int argc, char *argv[])
{
char mystr[N] ,result[N];
char ch;
int i,k;
k=0;
printf("enter string \n");
gets(mystr);///////////////////////////
//scanf("%s",&mystr);///////////////////
printf("enter char \n");
scanf("%c",&ch);
// scanf("%c",&ch);
for ( i = 0; i <= strlen(mystr); i++ )
{
if (mystr[i] != ch)
{
result[k]=mystr[i];
k++;
}
}
puts(result);
system("pause");
return 0;
}
Use this one:
char temp[2];
scanf("%1s",temp);
ch = temp[0];
and use gets
scanf when used with chars has some problems (it gets the "old" new line). Here we "cheat" a little and we use scanf to get a string that can have up to one character. A string of 1 character clearly needs a second character for the terminator, so an array of 2 characters.
Be aware that using a scanf for the character to search, you won't be able to insert the space character.
Note that gets is an "evil" function. You can easily do buffer overruns using it (it doesn't check that the buffer is big enough). The "right" way to do it is normally: fgets(mystr, N, stdin); (the "file" variant of gets has a maximum number of characters that can be read and will append a \0 at the end). Note that if you insert 150 characters in a fgets, 99 will go to your string (because you gave 100 of max size), 1x \0 will be appended and the other characters will remain in the buffer "ready" for the next scanf/gets/fgets... (to test it, reduce the buffer to a smaller value, like 5 characters, and do some tests)
You can use fgets() as suggested by xanatos with a small hack, so you can reliably handle return characters. Just change the '\n' to '\0' in the string obtained using fgets.
And in your program, you forgot to terminate the new string with a '\0'.
So here's the code you're looking for.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100
int main(int argc,char **argv){
char string[N],str1[N];
char ch;
int i,k = 0;
fgets(string,N,stdin);
string[strlen(string)-1] = '\0';
scanf("%c",&ch);
printf("\n%s , %c",string,ch);
for (i=0;i<=strlen(string);i++)
if(string[i] != ch)
str1[k++] = string[i];
str1[k] = '\0';
printf("\n%s , %s\n",string,str1);
return 0;
}

Resources