the output should be something like this:
Enter Character : a
Echo : a
I wrote
int c;
while (c != EOF)
{
printf("\n Enter input: ");
c = getchar();
putchar(c);
}
But I get two Enter Input after the echos.
Two characters are retrieved during input. You need to throw away the carriage return.
int c = 0;
int cr;
while (c != EOF)
{
printf("\n Enter input: ");
c = getchar();
cr = getchar(); /* Read and discard the carriage return */
putchar(c);
}
Homework?
If so, I won't give a complete answer/ You've probably got buffered input - the user needs to enter return before anything is handed back to your program. You need to find out how to turn this off.
(this is dependent on the environment of your program - if you could give more details of platform and how you are running the program, we could give better answers)
take fgets eg:
char c[2];
if( fgets( c, 2, stdin ) )
putchar( *c );
else
puts("EOF");
and you dont have any problems with getchar/scanf(%c)/'\n' and so on.
Why don't you use scanf instead?
Example:
char str[50];
printf("\n Enter input: ");
scanf("%[^\n]+", str);
printf(" Echo : %s", str);
return 0;
Outputs
Enter input: xx
Echo : xx
scanf reference
#include <stdio.h>
#include <conio.h>
main(){
int number;
char delimiter;
printf("enter a line of positive integers\n");
scanf("%d%c", &number, &delimiter);
while(delimiter!='\n'){
printf("%d", number);
scanf("%d%c", &number, &delimiter);
}
printf("\n");
getch();
}
Related
In similar questions, the scanf reading a char or string skips because it takes in a new line from the input buffer after the "Enter" key is pressed for the previous scanf, but I don't think that's the issue here. This program does not skip the 2nd scanf if input1 is an integer, but it skips it for other types of inputs (double, char, string, etc.).
#include <stdio.h>
#include <string.h>
int main(){
int input1;
char input2[6];
printf("Enter an integer. ");
scanf("%d", &input1);
printf("You chose %d\n", input1);
printf("Write the word 'hello' ");
scanf(" %s", input2);
if (strcmp(input2,"hello")==0){
printf("You wrote the word hello.\n");
} else {
printf("You did not write the word hello.\n");
}
return 0;
}
Why does this happen?
Comments in code:
int input1 = 0; // Always initialize the var, just in case user enter EOF
// (CTRL+D on unix) (CTRL + Z on Windows)
while (1) // Loop while invalid input
{
printf("Enter an integer. ");
int res = scanf("%d", &input1);
if ((res == 1) || (res == EOF))
{
break; // Correct input or aborted via EOF
}
int c;
// Flush stdin on invalid input
while ((c = getchar()) != '\n' && c != EOF);
}
printf("You chose %d\n", input1);
Also, take a look to How to avoid buffer overflow using scanf
Did you try to write "%*c" after your %c or %s or %d ?
Something like this : scanf("%s%*c", input1);
So my code does the following:
Ask what's the option
If option is 1: Scan some numbers
If option is 2: Print those numbers
After each option, ask if user wanted to continue choosing (Y/N)
This is my main code
while(yesnocheck==1)
{
printf("What's your option?: ");
scanf("%d",&b);
switch(b){
case 1:
printf("How many numbers?: ");
scanf(" %d",&n);
a=(struct sv*)malloc(n*sizeof(struct sv));
for(int i=0;i<n;i++)
scanf("%d",&((a+i)->num));
break;
case 2:
for(int i=0;i<n;i++)
printf("%d\n",(a+i)->num);
break;
}
yesnocheck==yesnochecker();
}
And this is the yesnochecker function:
int yesnochecker()
{
char yesorno;
printf("Do you want to continue? (Y/N)");
while(scanf("%s",&yesorno))
{
if(yesorno=='Y')
return 1;
if(yesorno='N')
return 0;
printf("*Wrong input. Please reenter (Y/N): ");
}
}
So on dev C++, my code won't run correctly. After it's done option 1, when I enter "Y" then choose option 2, case 2 will display some weird numbers. However it works well on online C compilers.
And then, when I change the char yesorno in yesnochecker() function to char yesorno[2] and treat it as a string, the code does work.
Can someone shed some light?
It is a bad idea to read a char c with scanf("%s", &c);. "%s" requires a buffer to store a string. The only string which fits into a char is an empty string (consisting only of a terminator '\0' – not very useful). Every string with 1 character requires 2 chars of storage – 1 for the character, 1 for the terminator ('\0'). Providing a char for storage is Undefined Behavior.
So, the first hint was to use the proper formatter instead – "%c".
This is better as it removes the Undefined Behavior. However, it doesn't solve another problem as the following sample shows:
#include <stdio.h>
int cont()
{
char c; do {
printf("Continue (y/n): ");
scanf("%c", &c);
printf("Input %c\n", c);
} while (c != 'y' && c != 'n');
return c == 'y';
}
int main()
{
int i = 0;
do {
printf("Loop iteration %d.\n", ++i);
} while (cont());
/* done */
return 0;
}
Output:
Loop iteration 1.
Continue (y/n): y↵
Input 'y'
Loop iteration 2.
Continue (y/n):
Input '
'
Continue (y/n): n↵
Input 'n'
Live Demo on ideone
WTH?
The scanf("%c") consumes one character from input. The other character (inserted for the ENTER key) stays in input buffer until next call of any input function.
Too bad, without ENTER it is hard to confirm input on console.
A possible solution is to read characters until the ENTER key is received (or input fails for any reasons). (And, btw., getc() or fgetc() can be used as well to read a single character.):
#include <stdio.h>
int cont()
{
int c;
do {
int d;
printf("Continue (y/n): ");
if ((c = fgetc(stdin)) < 0) {
fprintf(stderr, "Input failed!\n"); return 0;
}
printf("Input '%c'\n", c);
for (d = c; d != '\n';) {
if ((d = fgetc(stdin)) < 0) {
fprintf(stderr, "Input failed!\n"); return 0;
}
}
} while (c != 'y' && c != 'n');
return c == 'y';
}
int main()
{
int i = 0;
do {
printf("Loop iteration %d.\n", ++i);
} while (cont());
/* done */
return 0;
}
Output:
Loop iteration 1.
Continue (y/n): y↵
Input 'y'
Loop iteration 2.
Continue (y/n): Hello↵
Input 'H'
Continue (y/n): n↵
Input 'n'
Live Demo on ideone
Please, note, that I changed the type for the read character to int. This is because getc()/fgetc() return an int which is capable to store any of the 256 possible char values as well as -1 which is returned in case of failing.
However, it isn't any problem to compare an int with a character constant (e.g. 'y'). In C, the type of character constants is just int (SO: Type of character constant).
I'm new to C and I'm currently making a tutorial.
I have decided to combine two exercices and I want to take inputs
as long as I don't just do < return >. This is my code until now:
#include<stdio.h>
char letter;
int i=0;
int main() {
while (i==0) {
printf(">> ");
letter = getchar();
printf("%d\n", letter);
if (letter==10) { //10 is the ASCII id for <return>
printf("End\n");
i = 1;
}
printf("You've entered %c\n", letter);
}
}
The problems is that when I enter a letter for the first time, it does what I want it to do: take a number, and return it on the screen. Directly after that it sets 10 on it's on own!
This is the output:
>> r //I've entered 'r'
114
Das Zeichen ist r
>> 10 //I've entered nothing. It entered that on it's own
End
The letter is
What is going on here? Why does it do that? I didn't enter anything or pressed anything.
The reason that when you enter "r" you also press Enter ('\n' which equals to ASCII 10). The shortest way is to add another getchar() inserted to consume the '\n':
int main() {
while (i==0) {
printf(">> ");
letter = getchar();
getchar();
printf("%d\n", letter);
if (zeichen==10) { //10 is the ASCII id for <return>
printf("End\n");
i = 1;
}
printf("You've entered %c\n", letter);
}
}
There is also another short way which is comparing letter value early after it's assignment like following:
int main() {
while (i==0) {
printf(">> ");
letter = getchar();
if(letter == '\n')
continue;
printf("%d\n", letter);
if (zeichen==10) { //10 is the ASCII id for <return>
printf("End\n");
i = 1;
}
printf("You've entered %c\n", letter);
}
}
however you still need to assign zeichen to something otherwise you'll get undefined behavior
Standard portable C API are not good to handle keystrokes. To "enter r" you need to press "r" "return" so your program using getchar() will receive them both immediately. Your need to use ncurses or cornio.
while (i==0) {
printf(">> ");
letter = getchar();
printf("%d\n", letter);
if (zeichen==10) { //10 is the ASCII id for <return>
printf("End\n");
break;
}
Use break statement instead of i=1;
If using Windows, use _getch() from "conio.h"
Also, instead of checking for 10 (which is the linefeed character not Return), it is better to check for \r, which is what the ENTER key returns. Never use literal values when more descriptive escapes can be used:
line feed = \n
Return = \r
etc.
I have been asked to modify a program to read characters rather than numbers.
i modified the array into a char array. changed the two "%d" to "%c" as below
void main (void)
{
char a[100];
int counter;
int b;
counter = 0;
printf("please enter the length of the array: ");
scanf("%d", &b );
while (counter != b)
{
printf("please enter character: ");
scanf("%c", &a[counter]);
counter++;
}
a[counter] = '\0' ;
counter = 0;
while (a[counter] != '\0')
{
printf("\n");
printf("%c",a[counter]);
counter++;
}
}
when i run this the program does this:
please enter the length of the array: (4)
please enter character: please enter character: (a)
please enter character: please enter character: (a)
a
a
() are used to indicate the user inputs.
would be really good if i could get some help.
You have to remember that scanf leaves the newline in the input buffer, so when you try to read a character it will that newline.
The solution is very simple: Tell scanf to read and discard leading whitespace, by adding a space in the format code:
scanf(" %c", &a[counter]);
/* ^ */
/* | */
/* Note space here */
Can some one explain me why I see a double input of the printf() function the while loop:
#include <ctype.h>
#include <stdio.h>
int main(){
int x = 0;
while ( x != 'q'){
printf("\nEnter a letter:");
x=getchar();
printf("%c\n", x);
if( isalpha(x) )
printf( "You entered a letter of the alphabet\n" );
if( isdigit(x) )
printf( "You entered the digit %c\n", x);
}
return 0;
}
The output of the code in Debian Squeeze (gcc version 4.4.5 (Debian 4.4.5-8)) is:
Enter a letter:1
1
You entered the digit 1
Enter a letter: // why is the first one appearing ???
Enter a letter:2
2
You entered the digit 2
The first one reads the line terminator character you entered when hitting Enter after 1 (the line terminator will remain in the input buffer).
You can verify this by adding an else branch:
#include <ctype.h>
#include <stdio.h>
int main()
{
int x = 0;
while ( x != 'q')
{
printf("\nEnter a letter:");
x = getchar();
printf("%c\n", x);
if( isalpha(x) )
printf( "You entered a letter of the alphabet\n" );
else if( isdigit(x) )
printf( "You entered the digit %c\n", x);
else
printf("Neither letter, nor digit: %02X\n", x);
}
return 0;
}
The output:
Enter a letter:1
1
You entered the digit 1
Enter a letter:
Neither letter, nor digit: 0A
Enter a letter:2
The byte 0A is the line-feed character.
The second time through the loop, getchar() is getting the Enter after the first char you entered.
You could do something like
while ((c = getchar()) != EOF && c != '\n') {} /* eat the rest of the line */
to get rid of everything up to and including the next Enter after getting a char and before asking for another.
If you want to check characters as you enter a slightly advanced technique would be to change stdin's behavior to raw mode.Then as soon as the user hits a char you get that in your variable.
Check this for some start
Use CTRL + D to get the functionality of the newline character without its side effect.