Working of scanf and checking if input is int - c

I wanted to check whether input given is integer input or not. I did not wanted to store input in a string. After seeing several questions on stackoverflow and by hit and trial, I have created following code
while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
if(a == '\n')
scanf("%c",&a);
else
{
while(a != '\n')
scanf("%c",&a);
}
}
It works but according to my understanding, the following should have also worked
while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
while(a != '\n')
scanf("%c",&a);
}
Can someone please tell me why above did not worked ?? Also if someone has better solution please give it also.
Note :I am considering 12qwe also as an invalid input. I just want integers.

The problem with
while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
while(a != '\n')
scanf("%c",&a);
}
is that if a happens to contain '\n' before the scan, and the scan fails, the inner while loop doesn't run at all. So
if the scan failed trying to parse an int from the input stream because the input was e.g. "ab c\n", the offending input remains in the input stream, the next scanf in the outer while loop control fails parsing an int again, a remains '\n', repeat.
if an input error occurred before reading a character from the stream into a, the scanf in the outer loop control fails because of a corrupted stream, repeat.
In the other version,
while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
if(a == '\n')
scanf("%c",&a);
else
{
while(a != '\n')
scanf("%c",&a);
}
}
you make at least some progress as long as there is input to be read from the stream, since whatever a contains, you read at least one character from the input stream before attempting the next parsing of an int. It will also result in an infinite loop if the input stream is corrupted/closed/ends prematurely, e.g. if you redirect stdin from an empty file. You can have that loop also output multiple "Please enter an integer only : " messages by giving input like `"a\nb\nc\nd\n".
So you should check whether scanf encountered the end of the stream or some other read error before converting anything from the input, and abort in that case:
int reads;
while(((reads = scanf("%d%c", &num, &a)) != 2 && reads != EOF) || a != '\n')
{
printf("Please enter an integer only : ");
// read at least one character until the next newline
do {
reads = scanf("%c", &a);
}while(reads != EOF && a != '\n');
}

This is a wrong way to do. You can rather read the input using fgets() and then parse your string for integer ASCII range.
fgets(s, 1024, stdin)
for (i=0; s[i] ! = '\0';i++) {
if( s[i] <'0' && s[i] >'9')
// not an integer<br>
You can also use standard functions like isalnum, isalpha etc.

it works……
while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
do{
scanf("%c",&a);
}while(a != '\n');
}

Related

User input with scanf using while loop

I'm having a problem with multiple characters while using a while loop. I'm writing a code that would direct the user to a new function based on the input of either "y" or "n". When I scanf for one character it works fine; however, when the user types in multiple characters the while loop repeats.
#include <stdio.h>
int main()
{
char x;
printf("type in letter n or y\n");
scanf("%c", &x);
while (x!= 'Y' && x!='N' && x!= 'n' && x!='y')
{
printf("Invalid, please type Y/N to continue: \n");
scanf(" %c", &x);
}
if (x== 'Y' || x == 'y')
{
printf("y works");
}
if (x =='N' || x =='n')
{
printf("n works");
}
}
For example, if I type in hoyp, it would say "Invalid, ..." 2 times and then the "y works" would be written on the third line. How can the code be changed so that the invalid would only be said once, and the user must input again to allow the program to continue?
This is how scanf behaves. It keeps reading in all the characters you've entered. You can accept a string as input first using fgets and extract and check only its first character. fgets allows you to specify the exact number of characters to be read. I have first declared a char array of size 4096. This will work when the input is up to 4095 characters. You can adjust the size as per your needs.
#include <stdio.h>
int main()
{
char x, buffer[4096];
printf("type in letter n or y\n");
fgets(buffer, 4096, stdin);
x = buffer[0];
while (x!= 'Y' && x!='N' && x!= 'n' && x!='y')
{
printf("Invalid, please type Y/N to continue: \n");
fgets(buffer, 4096, stdin);
x = buffer[0];
}
if (x== 'Y' || x == 'y')
{
printf("y works");
}
if (x =='N' || x =='n')
{
printf("n works");
}
}
Here is my approach to the problem:
I have used fgets() instead of scanf(). See why
here.
I have used the suggestion by users jamesdlin and M.M in this question to solve the repeated printing issue when the input is more than one character or if the input is empty. I encourage you to read the whole thread to know more about this issue.
(Optional) Used some extra headers for better code readability in the loop conditions. I think the fgets() could be used in the condition of the while() but I got used to the pattern I have written below.
Edit: added a condition to reject inputs with length > 1. Previously, inputs that starts with 'y' or 'n' will be accepted (and are interpreted as 'y' or 'n' respectively) regardless of their length.
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
void clearInput();
int main()
{
// allocate space for 'Y' or 'N' + '\n' + the terminator '\0'
// only single inputs will be accepted
char _inputbuff[3];
char choice;
bool isValidInput = false;
while(!isValidInput) {
printf("Please enter your input[y/n]: ");
// use fgets() instead of scanf
// this only stores the first 2 characters of the input
fgets(_inputbuff, sizeof(_inputbuff), stdin);
// don't accept empty input to prevent hanging input
if(_inputbuff[0] == '\n') {
printf("Empty input\n");
// go back to the top of the loop
continue;
}
// input is non-empty
// if the allocated space for the newline does not
// contain '\n', reject the input
if(_inputbuff[1] != '\n') {
printf("Input is more than one char.\n");
clearInput();
continue;
}
choice = _inputbuff[0];
// printf("The input is %c\n", choice);
// convert the input to uppercase for a 'cleaner' code
// during input validation
choice = toupper(choice);
// the input is not 'Y' or 'N'
if(choice != 'Y' && choice != 'N') {
printf("Please choose from Y or N only.\n");
// go back to the top of the loop
continue;
}
// the input is 'Y' or 'N', terminate the loop
isValidInput = true;
}
// conditions for 'Y' or 'N'
if(choice == 'Y') {
printf("The input is Yes.\n");
return 0;
}
if(choice == 'N') {
printf("The input is No.\n");
return 0;
}
}
void clearInput() {
int _clear;
// clear input stream to prevent repeated printing of invalid inputs
while ((_clear = getchar()) != '\n' && _clear != EOF ) { }
}
(This is my first time answering a question and it has been a while since I have used C so feel free to give suggestions/corrections regarding my answer. Thanks!)

o count character entered through stdin first time it works for continuing the execution it is not readig the character

this code gives the output correctly for the first time but it is not reading the character for the second time execution scanf("%c"&op) is not reading the character for continuing the execution i tried with getchar(); and scanf(" %C",&op); but still it is not reading the input............................................................................
int main()
{
//declaring local variable
char op;
//do while for user interaction
do
{
//function call
count();
//asking if user want to continue execution
printf("\nDo you want to continue(Y/y):");
scanf(" %c",&op);
}while( op == 'Y' || op == 'y');
return 0;
}
int count()
{
char ch;
int word_count = 0, line_count = 0, char_count = 0;
//asking user for the input
puts("enter the sentence:");
//Loop to fetch the input
while( (ch =getchar()) != EOF)
{
//To count the number of characters
char_count++;
//If entered char is new line
if (ch == '\n')
{
//To count the number of lines in input
line_count++;
}
//To check if the entered input is space or tab or next line
if(ch == ' ' || ch == '\t' || ch == '\n' )
{
//Word count
word_count++;
//Get the char
ch = getchar();
//To check if the enter char is space or tab or new line
if(ch == ' ' || ch == '\t' || ch == '\n' )
{
//If the entrered char is space or tab or new line
word_count--;
}
//Returing the character to input stream
ungetc(ch,stdin);
}
}
//Printiong the number of char,word,line count
printf("\n");
printf("Line count\t: %d\n", line_count);
printf("Word count\t: %d\n", word_count);
printf("Character count\t: %d", char_count);
return 0;
}
For reading the character of the user's choice for continuation after you signaled EOF on the sentence input, you have to call clearerr(stdin) before the scanf(" %c",&op).
The clearerr function clears the end-of-file and error indicators for the stream …
Note that with your given scanf(" %c",&op), the newline character entered after y will be read as part of the next sentence, increasing the line count by one. To avoid this for the case where the user enters only a single choice character, you could use scanf(" %c%*c", &op). To handle also cases where the users enters more (e. g. yes), you could instead getchar() in a loop until \n or EOF.

Read single key input from keyboard and evaluate it

I want to read one keyboard input - and depending whether it is valid or not proceed with the operation or do something else. If it's invalid the input should be repeated.
At this point I'm aware already scanf is not the tool of my desire, but that here would be the default-code (if scanf would work as intended):
char val;
int incorrect = 0;
printf("Do you wish to proceed?: <Yy/Nn>");
do
{
incorrect = 0;
scanf(" %c", &val); //Changed to " %c" alread from "%c"
//getchar(); //Tried already, doesn't solve the problem
if (!(val == 'y' || val == 'Y' || val == 'n' || val == 'N'))
{
printf("Invalide Input!\n");
incorrect = 1;
}
} while (incorrect);
The problem is if instead of a one-character input there is a longer input the error-message will be repeated by the number of the characters.
Also, if instead of for instance 'n' the input is "nasdlfjas" it is still considered as a valid input.
Changing the scanf to val = getchar(); if (kind != EOF) (with or without the EOF-part) as suggested here doesn't change the behavior. But the Error-message is added right after the question.
The "GetStuff()" from this solution suffers from the same problem. The error-output is multiple and one single correct character in the whole input determines the result.
This variant however is doing better, but evaluates the result on the first character of the entire string.
Other variants which include a while((c = getchar()) != EOF); which is the preferred variant to use getchar have similar issues of going through the loop-body before the input of the character (and therefore printing the error).
I decided to read a string instead of a character and then just evaluate the result by dealing with the string itself. Something like:
do{
int c, line_length = 0;
int i = 0;
while ((c = getchar()) != EOF && c != '\n' && line_length < MAX_LINE - 1)
{
sentence[i++] = c;
line_length++;
}
// String Stuff
if (!(val == 'y' || val == 'Y' || val == 'n' || val == 'N'))
{
printf("Invalide Input!\n");
incorrect = 1;
}
} while (incorrect);
But again there will "Invalide Input!" be printed before entering anything.
What exactly would be the proper way to evaluate just the input of a single character?

How to only allow specific Input in C

My Code:
#include<stdio.h>
char checkInput0(void);
int main() {
char output;
output = checkInput0();
printf("The output is %c", output);
}
char checkInput0(void){
char option0 = '\0',check0;
char c;
do{
printf("Please enter your choice: ");
if(scanf("%c %c",option0, &c) != 'A' || c != 'B' ){
while((check0 = getchar()) != 0 && check0 != '\n' && check0 != EOF);
printf("[ERR] Please enter A or B.\n");
}else{
break;
}
}while(1);
return option0;
}
I would like to only allow the user to input only "A" or "B" and if anything else would be entered I would like to reprompt the user with the following message: [ERR] Please enter A or B.\n
I have written a funktion which worked with numbers but I can't get the one above (checkInput0) to work, what have I done wrong
scanf does not return c, it returns the number of variables successfully set. Comparing that to 'A' is pretty pointless.
Change your scanf call to scanf("%c %c", &option0, &c): currently the behaviour is undefined: the variable arguments need to be pointer types.
x != 'A' || x != 'B' is 1 for any value of x.
Consider moving scanf outside the if conditional: checking the return value of scanf explicitly. On the third point, did you want &&?
Also be careful with ace code that writes c on one side of an operator, and reads it on the other. It's fine in this instance since || is a sequencing point, but you are quite close to undefined behaviour here.

C user input only integers, return value from scanf

I am trying to get some user input, and I want to make sure that they enter integers, and if they don't I will just ask them to type again (loop until they get it right).
I have found a lot of different approaches to do this; some more complicated then others. But I found this approach which seems to work.
But I just don't really get why this is tested in the code:
scanf("%d%c", &num, &term) != 2
I can understand that scanf outputs the number of items successfully matched and assigned, but I don't get why it outputs 2 if it is an integer.
The code in C is:
int main(void)
{
int num;
char term;
if (scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");
}
Trying to put it in loop:
int main(void){
int m, n, dis;
char m_check, n_check, dis_check;
do{
m = 0; n = 0; dis = 0;
m_check = ' '; n_check = ' '; dis_check = ' ';
printf("Please enter number of rows m in the matrix (integer): ");
if(scanf("%d%c", &m, &m_check) !=2 || m_check != '\n')
m_check = 'F';
printf("Please enter number of columns n in the matrix (integer): ");
if(scanf("%d%c", &n, &n_check) !=2 || n_check != '\n')
n_check = 'F';
printf("Should the random numbers come from a uniform or normal distribution?...
Please press 1 for uniform or 2 for normal: ");
if(scanf("%d%c", &dis, &dis_check) !=2 || dis_check != '\n' || dis != 1 || dis !=2)
dis_check = 'F';
}while(m_check == 'F' || n_check == 'F' || dis_check == 'F');
I've tried just inputting m = 3, n = 3, dis = 2, and then the loop just starts over and asks me to input number of rows. And if I when asked for this press f or something it just start looping like crazy over the printf-statements :)
scanf returns the number of fields it converted. You have the format string %d%c; it has:
%d - first field
%c - second field
so scanf returns 2.
If the user enters a number e.g. 123 and presses Enter, your num will be equal to 123, and term will be \n.
If the user enters a number with garbage at the end, e.g. 123garbage and presses Enter, your num will be equal to 123, the term will be g, and arbage\n will remain in the input buffer.
In both cases, scanf read an int and a char, so it returns 2.
A different example: the user enters garbage123. In this case, scanf will fail to read an integer, and return 0.
So your code checks for two different forms of incorrect output.
Entering an integer will match to the formatter %d and will assign the value to the variable num. The %c formatter will take the newline character ('\n') and store it in the variable term. scanf returns 2 cause 2 elements where correctly assigned (num and term)
If you don't enter an integer the formatter %d won't match correctly, and scanf won't return 2, producing a failure
Edit: Your do-while loop goes crazy cause your conditions in the last scanf are wrong (dis != 1 || dis !=2). It should be
if(scanf("%d%c", &dis, &dis_check) !=2 || dis_check != '\n' || (dis != 1 && dis !=2))
scanf("%d%c", &num, &term) != 2
This checks the return value of scanf . It will return number of arguments correctly matched . So , if a integer and a character is entered , they are store in vairables num and term and scanf returns 2 .
scanf will not return 2 if both the arguments are not correctly matched , in that case failure will be displayed as output.
Oops - now see OP wants to know why approached failed and was not necessarily looking for a how-to do it. Leaving this up as a reference as it does assert the fundamental problem: scanf(). Do not use it for user input.
If code truly needs to "get some user input, and wants to make sure that they enter integers", then use fgets() to get the line and then process the input.
Mixing user input with scanning/parse invariably results in some user input defeating the check, extra user input in stdin or improperly waiting for more input.
// true implies success
bool Read_int(int *value) {
char buffer[100];
if (fgets(buffer, sizeof buffer, stdin) == NULL) return false; // EOF or error
// Now parse the input
char *endptr;
errno = 0;
long number = strtol(buffer, &endptr, 10);
if (errno) return false; // long overflow
if (number < INT_MIN || number > INT_MAX) return false; // int overflow
if (endptr == buffer) return false; // No conversion
while (isspace((unsigned char) *endptr)) endptr++;
if (*endptr) return false; // non-white-space after number
*value = (int) number;
return true;
}

Resources