How to prevent '\n' being passed as input? - c

When we execute the following code:
#include <stdio.h>
int main(void){
char x,y;
scanf("%c", &y);
x = getchar();
putchar(x);
return 0;
}
The enter that is being inputted in the scanf("%c", &y); statement is passed on to x. Is there some way to get away with this? I now that if we are using scanf then we can ignore the \n by scanf("%*c%c", &x); but don't know what do while using getchar().

You can do something like this
#include <stdio.h>
int main(void)
{
char x,y,ch;
scanf("%c%*c", &y);
while((ch=getchar())!='\n'&&ch!=EOF); //removes all character in input buffer
x = getchar();
putchar(x);
return 0;
}

It's basically the problem of the input buffer, In your case, you can use alternative input-string getchar() with fflush(stdin); for handling this issue.

Related

What is rewind(stdin) for and why does C need it?

From my understanding, I need to write rewind(stdin) after inputting integers if I want to input char or string. Why do I need to do this and why can't C let me input a char after inputting int
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)
#include<math.h>
void main()
{
char c;
int x, y,square;
double root;
do {
printf("Enter integers = ");
scanf("%d%d", &x, &y);
square = pow(x, y);
root = double(sqrt(square));
printf("Squared = %d\n", square);
printf("Square root = %.2lf\n", root);
rewind(stdin); // If this isnt here it goes straight into the beginning instead of letting me input a char.
printf("Continue ? (Y/N)");
scanf("%c", &c);
} while (c != 'N' );
}
As comments already pointed out, there's a remain new-line character at scanf("%c", &c).
What I want to mention why rewind(stdin) make your code works is that rewind(stdin) moves input buffer position and, for some streams, it truncates its internal buffer. That's why your code works correctly with rewind(stdin) since it empties remaining characters in the buffer.
You can have the same effect with the following code which also moves its its input buffer position.
printf("Enter integers = ");
scanf("%d %d", &x, &y);
fseek(stdin, 0, SEEK_SET);
but, I found the following code has no effect with undefined behavior on Windows.
printf("Enter integers = ");
scanf("%d %d", &x, &y);
fflush(stdin)

Taking a string input using gets() function in C [duplicate]

I'm pretty new to C, and I have a problem with inputing data to the program.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
It allows to input ID, but it just skips the rest of the input. If I change the order like this:
printf("Input your name: ");
gets(b);
printf("Input your ID: ");
scanf("%d", &a);
It will work. Although, I CANNOT change order and I need it just as-is. Can someone help me ? Maybe I need to use some other functions. Thanks!
Try:
scanf("%d\n", &a);
gets only reads the '\n' that scanf leaves in. Also, you should use fgets not gets: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/ to avoid possible buffer overflows.
Edit:
if the above doesn't work, try:
...
scanf("%d", &a);
getc(stdin);
...
scanf doesn't consume the newline and is thus a natural enemy of fgets. Don't put them together without a good hack. Both of these options will work:
// Option 1 - eat the newline
scanf("%d", &a);
getchar(); // reads the newline character
// Option 2 - use fgets, then scan what was read
char tmp[50];
fgets(tmp, 50, stdin);
sscanf(tmp, "%d", &a);
// note that you might have read too many characters at this point and
// must interprete them, too
scanf will not consume \n so it will be taken by the gets which follows the scanf. flush the input stream after scanf like this.
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
fflush(stdin);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
getchar();
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
return 0;
}
Note:
If you use the scanf first and the fgets second, it will give problem only. It will not read the second character for the gets function.
If you press enter, after give the input for scanf, that enter character will be consider as a input f or fgets.
you should do this way.
fgetc(stdin);
scanf("%c",&c);
if(c!='y')
{
break;
}
fgetc(stdin);
to read input from scanf after reading through gets.
scanf("%d", &a); can't read the return, because %d accepts only decimal integer. So you add a \n at the beginning of the next scanf to ignore the last \n inside the buffer.
Then, scanf("\n%s", b); now can reads the string without problem, but scanf stops to read when find a white space. So, change the %s to %[^\n]. It means: "read everthing but \n"
scanf("\n%[^\n]", b);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
scanf("\n%[^\n]", b);
//first \n says to ignore last 'return'
//%[^\n] read until find a 'return'
printf("---------\n");
printf("Name: %s\n\n", b);
system("pause");
return 0;
}
The scanf function removes whitespace automatically before trying to parse things other than characters. %c, %n, %[] are exceptions that do not remove leading whitespace.gets is reading the newline left by previous scanf. Catch the newline usinggetchar();
scanf("%d", &a);
getchar(); // catches the newline character omitted by scanf("%d")
gets(b);
https://wpollock.com/CPlus/PrintfRef.htm
Just use 2 gets() functions
When you want to use gets() after a scanf(), you make sure that you use 2 of the gets() functions and for the above case write your code like:
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
//the change is here*********************
printf("Input your name: ");
gets(b);
gets(b);
//the change is here*********************
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}

Why does this scanf in a while loop work?

I can't understand why this does exactly what I want. The part where I used two scanf's in the loop confuses me. I compiled it using devcpp.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int dend, dsor, q, r;
char c;
while(c!='n')
{
printf("enter dividend: ");
scanf("%d", &dend);
printf("enter divisor: ");
scanf("%d", &dsor);
q=dend/dsor;
r=dend%dsor;
printf("quotient is %d\n", q);
printf("remainder is %d\n", r);
scanf("%c", &c);
printf("continue? (y/n)\n");
scanf("%c", &c);
}
system("PAUSE");
return 0;
}
FWIW, your code invokes undefined behavior. In the part
char c;
while(c!='n')
c is an uninitialized local variable with automatic storage and you're trying to use the value of c while it is indeterminate.
That said, first scanf("%c", &c); is used to eat up the newline present in the input buffer due to the press of enter key after previous input. You can read about it in details in another post.

Program not returning scanned character

So in my class, part of the homework assignment is to have a function that will return a character that's been entered.
I tried to create this sample code, but it's not working as I hoped.
#include <stdio.h>
char readCharacter();
int main(){
char x;
x = readCharacter();
printf("You inputted %c", x);
return 0;
}
char readCharacter(){
char z;
printf("Input character\n");
scanf("% c", &z);
return z;
}
I enter a character, I decided to type w, and the program told me the character was some weird funky font.
The actual code from my homework, or rather a snippet from it, is
#include <stdio.h> // needed by printf, scanf()
#include <ctype.h> // needed by tolower()
#include <stdlib.h> // for exit()
double readNumber(char *prompt) {
double val;
printf("%s", prompt);
scanf("% lf", &val);
//if input is not a number, exit program
if (scanf("%lf", &val) != 1) {
printf("Invalid input.\n");
exit(1);
}
return val;
}
char readYesOrNo(char* prompt) {
char yn;
printf("%s\n", prompt);
scanf("% c", &yn);
return yn;
}
int main() {
double bonus;
char yesNo;
yesNo = readYesOrNo("Did the worker get a bonus ? (y/n) ");
if (yesNo == 'y' || yesNo == 'Y') {
bonus = readNumber("Enter bonus: ");
}
else {
bonus = 0;
}
return 0;
}
In the actual homework code, the readYesOrNo function doesn't even wait for me to input anything, it just displays the prompt asking for a y/n response, then goes on to the next line of code, not waiting for user input and assuming a no response.
I have no clue why this isn't working.
% c is not a valid format specifier. But %c is probably what you meant.
This line:
scanf("% c", &z);
Needs to be this:
scanf("%c", &z);

Why procedure if in C doesn't work with char

I am writing a simple quiz in C (using CodeBlocks 13.12)
It compiles, but doesn't work in second question. Whatever I will input, it always give answer 'that's sad'.
I can't understand what is wrong.
I came to this, where if I comment line 13 ( scanf("%d", &age); ) it's starting works ok for second question.
What the problem is?
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <clocale>
int main()
{
int age;
char S1;
printf("How old is your dog? \n");
scanf("%d", &age);
if (age <= 7)
{
printf(" very young. the end \n");
return 0;
}
else
{
printf("old dog. \n \n");
}
//question2
printf("Do you like dogs? y/n \n");
scanf("%c%c", &S1);
if (S1 == 'y')
{
printf("hey, that's nice \n");
}
else
{
printf(" that's sad :( . \n");
return 0;
}
return 0;
}
You cause undefined behavior by
scanf("%c%c", &S1);
scanf reads two chars, one stored in S1, one stored in some location on the stack because scanf expects a second char* to be supplied.
If your intention is to ignore the newline following the actual character, write
scanf("%c%*c", &S1);
Change the second scanf() to
scanf(" %c", &S1);
This would escape the left out newline character \n in the input buffer.
Plus, you are reading one char in this. So you need only one %c
scanf("%c", &S1);
is the correct way to input one character ,

Resources