Why does getchar() return -1? - c

In the following code, why are the values of ch2 and ch3 equal to -1?
char ch1;
char ch2;
char ch3;
printf("put Type: ");
ch1 = getchar();
_flushall();
printf("put Type: ");
ch2 = getchar();
_flushall();
printf("put Type: ");
ch3 = getchar();
printf("\n");
printf("the ascii value for this three types is: %d, %d, %d", ch1, ch2, ch3);

If getchar encounters an error, it returns EOF (which is a macro that expands into an int with a negative value, typically "-1"). This explains why you see the -1.
As to why getchar fails, this is a separate question. Usually it means that it has reached the end of the input stream. I assume this has something to do with the fact that you're flushing it with _flushall?

Related

Why does the number 10 get output in each iteration and how can I fix this?

I have a for loop, which I want to get the input from the user and print the associated ascii value. But it only asks for the user input in the second iteration, which is followed and preceded by the output 10. I tried to get rid of new-line characters, but it still prints out 10.
#include <stdio.h>
int main(void){
int number;
printf("Enter the number:");
scanf("%i", &number);
for( ; number > 0; number--){
char character;
printf("Give a char: \n");
scanf("%c", &character);
printf("The associated ascii value is %i \n", character);
}
return 0;
}
Maybe simpler (though using scanf() for user input is not recommended)
scanf(" %c", &character);
// ^ skip otional leading whitespace
Your whole program using fgets() for user input (and my indentation, spacing, style; sorry)
#include <stdio.h> // printf(), fgets()
#include <stdlib.h> // strtol()
int main(void) {
int number;
char buffer[100]; // space enough
printf("Enter the number:");
fgets(buffer, sizeof buffer, stdin);
number = strtol(buffer, 0, 10); // error checking missing
for (; number > 0; number--) {
printf("Give a char: ");
fgets(buffer, sizeof buffer, stdin); // reuse buffer, error checking missing
if (buffer[0] != '\n') {
printf("The associated ascii value of '%c' is %i.\n", *buffer, *buffer);
}
}
return 0;
}
This should solve your problem. getchar() will read the extra newline character from buffer.
#include <stdio.h>
int main(void){
int number;
printf("Enter the number:");
scanf("%i", &number);
for( ; number > 0; number--){
char character;
printf("Give a char: ");
getchar();
scanf("%c", &character);
printf("The associated ascii value is %i \n", character);
}
return 0;
}
regarding;
scanf("%c", &character);
the first time through the loop the '\n' is input.
on all following passes through the loop, the scanf() fails, so the value in character does not change.
This is a prime example of why your code should be error checking.
for instance, to error check the call to scanf():
if( scanf("%c", &character) != 1 )
{
fprintf( stderr, "scanf for a character failed\n" );
break;
}
the 1 is because the scanf() family of functions returns the number of successful: input format conversion specifiers or EOF and it is best to assure the 'positive' status.

getchar following scanf (to read an integer) takes terminating "enter" key of scanf as character

When I have a scanf followed by a getchar, why does the getchar always keep getting the last delimiting character of scanf? How can I stop that? I tried looking into "format specifiers" for scanf, read quite a few things but none solves this.
The code is shown below -
#include <stdio.h>
#include <conio.h>
int main()
{
int a;
char b;
printf ("Enter an integer \n");
scanf_s(" %d", &a);
printf("Enter a character \n");
b = getchar();
printf("The integer you entered is %d \n", a);
printf("The character you entered is %c \n", b);
_getch();
return 0;
}
The output is as below -
Enter an integer
4563
Enter a character
The integer you entered is 4563
The character you entered is
The enter key I press at the end of integer entry is being returned by getchar. The screen does not even stop after printing "Enter a character". What is the correct way to do this ?
Use the scanf(" %c", &b) instead of getchar()
When you put the space befor the %c you clean the buffer
Or you can clean the buffer using this too:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
Complete example:
int main(void)
{
printf("Enter an integer \n");
int a;
scanf(" %d", &a);
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
}
printf("Enter a character \n");
char b = getchar();
printf("The integer you entered is %d \n", a);
printf("The character you entered is %c \n", b);
_getch();
}
But I think the scanf()

Clearing input buffer/garbage?

In this program, when I enter 8 characters, it screws up the whole program, and I think it has something to do with clearing the input buffer when you enter more than or equal to SIZE characters, how do I make it so that it clears any overflow of characters a user may enter?
Thanks for any help!
#include <stdio.h>
#define SIZE 8
int CharIsAt(char *pStr,char ch,int loc[],int mLoc);
int main(void){
char array[SIZE],search;
int found[SIZE],i,charsFound;
printf("Enter a line of text(empty line to quit): ");
while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){ //Loop until nothing is entered
printf("Enter a character to search: ");
search=getchar();
charsFound=CharIsAt(array,search,found,SIZE);
printf("Entered text: ");
fputs(array,stdout); //Prints text inputted
printf("Character being searched for: %c\n",search); //Prints character being searched for
printf("Character found at %d location(s).\n",charsFound); //Prints # of found characters
//Prints the location of the characters found relative to start of line
for (i=0;i<charsFound;i++)
printf("'%c' was found at %d\n",search,found[i]);
if (fgets(array,SIZE,stdin)==NULL) //Makes loop re-prompt
break;
printf("\nEnter a line of text(empty line to quit): ");
}
return 0;
}
int CharIsAt(char *pStr,char ch,int loc[],int mLoc){
//Searches for ch in *pStr by incrementing a pointer to access
//and compare each character in *pStr to ch.
int i,x;
for (i=0,x=0;i<mLoc;i++){
if (*(pStr+i)==ch){
//Stores index of ch's location to loc
loc[x]=i;
x++; //Increment for each time ch was counted in pStr
}
}
//Returns the number of times ch was found
return x;
}

char not working as expected in c [duplicate]

This question already has an answer here:
How to read / parse input in C? The FAQ
(1 answer)
Closed 6 years ago.
Hi consider the simple program below:
int main(void)
{
//exercise 1
float num2;
printf("please enter a number \n");
scanf_s("%f", &num2);
printf("the number multiple by 3 is %3.3f\n", num2 * 3);
//exercise 2
char ch1, ch2, ch3, ch4;
printf("enter a word with four char\n");
ch1 = getchar();
ch2 = getchar();
ch3 = getchar();
ch4 = getchar();
printf("the chars in reverse order are\n");
putchar(ch4);
putchar(ch3);
putchar(ch2);
putchar(ch1);
putchar('\n');
}
the output is:
please enter a number
2
the number multiple by 3 is 6.000
enter a word with four char
ffff
the chars in reverse order are
fff
3 chars printed to the console, if i move the code block of exercise 2 above 1:
int main(void)
{
//exercise 2
char ch1, ch2, ch3, ch4;
printf("enter a word with four char\n");
ch1 = getchar();
ch2 = getchar();
ch3 = getchar();
ch4 = getchar();
printf("the chars in reverse order are\n");
putchar(ch4);
putchar(ch3);
putchar(ch2);
putchar(ch1);
putchar('\n');
//exercise 1
float num2;
printf("please enter a number \n");
scanf_s("%f", &num2);
printf("the number multiple by 3 is %3.3f\n", num2 * 3);
}
the result as expected:
enter a word with four char
ffff
the chars in reverse order are
ffff
please enter a number
2
the number multiple by 3 is 6.000
i want to know why it's working when i change the order the code block and how can i solve it, thank you.
want to know why it's working when i change the order the code block and how can i solve it,
That's because scanf_s("%f", &num2); leaves newline character in the input buffer. So your first getchar(); will interpret that newline as ch1.
For this case, a silent preceding getchar would do:
getchar(); // will consume the remaining newline from stdin
ch1 = getchar();
ch2 = getchar();
ch3 = getchar();
ch4 = getchar();
There is a newline character when you input the first floating number, and it is input as a char by the call to getchar. Another way to fix this is to get entire line as a string using fgets, then parse it with whatever format you want:
char line[512];
printf("please enter a number \n");
fgets(line, sizeof line, stdin); // the newline is consumed here
sscanf(line, "%f", &num2);
ch1 = getchar(); // working as expected

Printing ASCII-code values and their equivalent chars in C

How could I print char for given ASCII code value?..
I saw this question, my problem is similar, just contrary
Below is my program, but it doesn't work.
int main (){
int code; // code that user enters
char ch; //"codes" related ASCII charcter
printf("Enter a ASCII code value: \n");
scanf("%d", &code);
ch=code;
printf(" %c is cherechter that have %d ASCII code\n", &ch ,&code);
system("PAUSE");
return 0;}
In your code, you have to change your printf statement
printf(" %c is cherechter that have %d ASCII code\n", &ch ,&code);
to
printf(" %c is cherechter that have %d ASCII code\n", ch ,code);
because, to print the values, you don't need to supply the address of the variables. The variable name is enough.
Change your code to:
int main (){
char code; //change from int to char
char ch;
printf("Enter a ASCII code value: \n");
scanf("%c", &code);//ASCII is a character not integer
ch=code;
printf(" %c is cherechter that have %x and %d ASCII code\n", ch ,code,code);//don't print the address access the value
system("PAUSE");
return 0;}

Resources