C - Why am I getting two characters excpet one as output? - c

So I create this small program to represent my problem. Run program enter 'a' press ENTER.
C Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char o;
while(1)
{
printf("> ");
scanf("%c",&o);
switch(o)
{
case 'a' :
printf("%c\n",o);
break;
case 'q' :
return 0;
}
}
}
Output is:
> a
a
> > *(waiting for input)*
What I expected it to be:
> a
a
> *(waiting for input)*
Please give me some advice how to get my problem solved. Thank you.

There is a \n on stdin after you scan out a. Either call getchar() after you have grabbed the character or change your scanf to scanf("%c%*c", &o). Because of this, the second time your loop looks for input, it will already have the \n waiting, and it will switch on that value, do nothing, and prompt again.

scanf("%c",&o); will read exactly one character, without skipping whitespace. In other words, it will treat newlines, tabs, and space characters as valid inputs.
To skip the whitespace characters, use
scanf(" %c",&o);
^---- note the extra space here

Add getchar() after your scanf.

After you type the input and hit 'Enter', the '\n' gets stored in the input buffer, and the next scanf takes '\n' as the input. Hence, you first need to get rid of the newline character. This can be achieved by using another variable (clr in the code below) to store the newline character. Here's the modification :
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char o,clr;
while(1)
{
printf("> ");
scanf("%c",&o);
clr=getchar(); // line added
switch(o)
{
case 'a' :
printf("%c\n",o);
break;
case 'q' :
return 0;
}
}
}

Related

C : How to stop the loop when getting the end of input from keyboard or file while using scanf one char at a time

void main(void)
{
char character;
do {
scanf("%c", &character);
printf("%c", character);
} while (character != EOF);
}
I'm going to process the input character by character, and I am only allowed to use scanf(). However, the while loop does not stop. Since I may need to process the input with multiple-line strings, it is impossible to add one more condition: character != '\n'.
Can somebody help me with this problem? Thanks!
You have an incorrect expectation. When scanf() encounters the end of the input before either matching an input item or recognizing a matching failure, it returns EOF. Under no circumstance does it modify the value of the datum associated with an input item that has not been matched.
You are ignoring scanf's return value, which is generally a perilous thing to do, and instead testing whether scanf records EOF in the object associated with the input item, which, in your particular case, it must not ever do.
For a start it should be int main...
Also you need to check the return value from scanf - please read the manual page.
Taking this into account, the code should look like this
#include <stdlib.h>
#include <stdio.h>
int main()
{
char character;
while (scanf("%c", &character) == 1) {
if (character != '\n) {
printf("%c", character)
}
}
return EXIT_SUCCESS;
}

scanf not working correclty in this c program

I have wrote a small code to get value from Fahrenheit to Celsius. I wanted to keep inputting data until I press any other key than 'y'. But this loop doesn't work that way and stops after one iteration.
#include <stdio.h>
int main()
{
char ch='y';
int far, cen;
do {
printf("again\n");
scanf("%d",&far);
//cen = (5.0/9.0)*(far-32);//integer division will truncate to zero so we can make 5/9 to 5.0 / 9.0
cen = (5*(far-32))/9;//or this way we can use this formula
printf("\n%d\t%d",far, cen);
printf("ch=%c",ch);
scanf("%c",&ch);
}while(ch == 'y');
return 0;
}
What is the problem here?
P.S
I added a line and made a new code like this
#include <stdio.h>
int main()
{
char ch='y';
int far, cen;
do {
printf("again\n");
scanf("%d",&far);//here we press carriage return. this value is in stdin
//cen = (5.0/9.0)*(far-32);//integer division will truncate to zero so we can make 5/9 to 5.0 / 9.0
cen = (5*(far-32))/9;//or this way we can use this formula
printf("\n%d\t%d",far, cen);
scanf("%c",&ch);//putting a space before %c makes the newline to be consumed and now it will work well
if((ch == '\r')|| (ch == '\n'))
printf("1\n");
printf("ch=%c",ch);//this takes the carriage return in stdin buffer
}while(ch == 'y');
return 0;
}
I need to know carriage return here is \r or \n?
When the value for scanf("%d",&far); is entered and press enter, the scanf stores the carriage return in the buffer. When it encounters the second scanf in the code scanf("%c",&ch); it takes the carriage return present in the buffer as the input to 'ch'. So it doesn't wait for the user input.
Please have a look at the post here
As indicated in one of the reply the solution is to put a space in scanf
scanf(" %c",&ch);
You should always check the return value of scanf. Your first use of scanf may fail if the user does not enter a valid integer, in which case, you are using far without initialising it (which is undefined behaviour). scanf returns the number of items that were successfully scanned. If you are requesting scanf to scan one integer, then it should return 1 if it successfully managed to scan an integer.
int scanresult = scanf("%d", &far);
if (scanresult != 1)
{
puts("Invalid input or unexpected end of input");
return 1;
}
In addition, the %c conversion specifier is unique in that it does not cause scanf to gobble up any preceding whitespace unlike the other conversion specifiers. To force scanf to gobble up the whitespace (such as linefeeds, carriage returns, spaces, tabs etc), simply put a space character before the %c, e.g.
scanresult = scanf(" %c", &ch);
For scanf, the space character is actually a directive to parse and skip all whitespace.
This is because of the previous newline character remaining in the buffer. You can simply replace scanf by this line:
while((ch = getchar()) == '\n');
You'll be needing the same technique in combination with ungetc() in many occasions.
Add fflush() function, just above scanf("%c", &ch). Because buffer of CONSOLE INPUT stores characters that not returned to program. Which is ENTER pressed in previous scanf:
#include <stdio.h>
int main() {
char ch='y';
int far, cen;
do {
printf("again\n");
scanf("%d",&far);
//cen = (5.0/9.0)*(far-32);//integer division will truncate to zero so we can make 5/9 to 5.0 / 9.0
cen = (5*(far-32))/9;//or this way we can use this formula
printf("\n%d\t%d",far, cen);
printf("ch=%c",ch);
scanf("%c",&ch); // This scanf will be ignored, because loads last
// character from buffer that can be recognized
// by scanf which is pressed "ENTER" from previous scanf
printf("%d", ch) // Shows 10, which is ASCII code of newline
fflush(stdin); // Clear buffer
scanf("%c",&ch); // Now it will prompt you to type your character.
// printf("%c"ch); //Without fflush, it must show 10, which is \n code
}while(ch == 'y');
return 0;
}
if after Y you press "space" or "return" this is the character you will find in %C

Empty string ends for loop

What's wrong in the below program (What's happening here)? It should break the for loop after the user inserts empty string (presses only ENTER), but in my case it ends in endless for loop. I tried what is in the comments with no success.
#include <stdio.h>
#include <string.h>
struct S {
char str [10];
};
int main(void)
{
int n;
struct S strings [10];
for (n = 0; n < 10; n++) {
# fflush(stdout);
scanf("%s", strings[n].str);
if (strlen(strings[n].str) == 0)
break;
# getchar();
}
printf("done");
return 0;
}
When I replace scanf with gets(strings[n].str); done is never printed. How would you fix it?
This sample solution works. Is there a difference in comparison to my code?
The enter key is not empty string, it is an ascii character or rather two characters a CR and LF (on Windows).
You shouldn't use strlen to find out if the input is empty. As others have said, when you press ENTER you get one or two characters sent to you.
You could instead check the first character in the string and see if it is '\n' or '\r'
scanf returns exactly what you've input... i.e. a crlf pair I'd imagine!
The problem with using scanf is that it expects something, not an empty string. You solve this by using e.g. fgets instead of scanf:
if (fgets(strings[n].str, sizeof(strings[n].str), stdin))
{
/* You got a string, it will contain the newline! */
}

can any one explain the output of this program?

Why does following program produce two output message at the same time, without asking for any input from the user???
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char input;
do {
printf("Enter a single character: \n");
scanf("%c", &input);
printf("The ordinal value is %d. \n",input);
} while(input != '#');
return 0;
}
The output is followings:
Enter a single character:
s
The ordinal value is 115.
Enter a single character:
The ordinal value is 10.
Enter a single character:
Terminal input is read line at a time unless you specify otherwise; scanf reads one character as specified, leaving the newline you typed afterward to send the line in the input buffer for the next pass of the loop. Consider reading input by lines and using sscanf() or similar to parse those lines.
Just insert getchar(); after your call to scanf. This will eat the newline. The suggestion to use scanf("%c\n", &input); seems sound, but I've never found it to work well; I wonder if anyone can tell me why?

get user input (terminate by enter key)

i use a scanf to get user input but if i press enter, the cursor will flash to next line~
what function should i use instead of scanf if i want the program will terminated if the users only press enter without keying any thing?
thanks
Scanf reads until the next token -- it doesn't really care about newlines at all (just considers them to be whitespace, like spaces or tabs).
Instead, use a line-reading function like fgets.
you can use gets() function in this way :
#include <stdio.h>
#define MAX_INPUT_CHAR 100
int main( ) {
char str[MAX_INPUT_CHAR ];
printf( "Enter a value :");
gets( str );
return 0;
}
Function char *gets(char *s) reads a line from stdin into the buffer pointed to by
s until either a terminating newline or EOF (End of File)
Pay attention gets() is not safe. You can't now apriori how much character it will read. This can cause some security problem and eventually crash.
Just use this code :
char ch;
printf("Enter Your Sentence \n");
while (1)
{
ch = getch();
if ((int)ch == 13)
break;
printf("%c", ch);
}
I disagree:
char * x;
scanf("%s",x);
printf("Inserted line: %s\n",x);
Will store in x only the characters till the return key.
I build it and runned it and it works.

Resources