Trying to Use a While Statement to Validate User Input C++

While loop to validate input is a number in C?

If scanf fails to preform the requested conversion, it will leave the input stream unchanged. So while your check is correct, you need to clean the input stream of the erroneous input before re-attempting to read a number again.

You can do it with scanf itself and and the input suppression modifier:

float num1;
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number: ");
scanf("%*s");
}

%*s will instruct scanf to parse the input as though it's attempting to convert a string of characters (removing characters in the process from the stream), but thanks to the asterisk, it won't attempt to write it anywhere.

Validate the type of input in a do-while loop

The problem is that "scanf()" can leave unread data in your input buffer. Hence the "infinite loop".

Another issue is that you should validate the return value from scanf(). If you expect one integer value ... and scanf returns "0" items read ... then you know something went wrong.

Here is an example:

#include <stdio.h>

void discard_junk ()
{
int c;
while((c = getchar()) != '\n' && c != EOF)
;
}

int main (int argc, char *argv[])
{
int integer, i;
do {
printf("Enter > ");
i = scanf("%d", &integer);
if (i == 1) {
printf ("Good value: %d\n", integer);
}
else {
printf ("BAD VALUE, i=%i!\n", i);
discard_junk ();
}
} while (i != 1);

return 0;
}

Sample output:

Enter > A
BAD VALUE, i=0!
Enter > B
BAD VALUE, i=0!
Enter > 1
Good value: 1

'Hope that helps!

Trying to use a while statement to validate user input C++

This is an annoying problem with cin (and istreams in general). cin is type safe so if you give it the wrong type it will fail. As you said a really large number or non-number input it gets stuck in an infinite loop. This is because those are incompatible with whatever type levelChoose may be. cin fails but the buffer is still filled with what you typed so cin keeps trying to read it. You end up in an infinite loop.

To fix this, you need to clear the fail bit and ignore all the characters in the buffer. The code below should do this (although I haven't tested it):

while(levelChoose > 10 || isalpha(levelChoose))
{
cout << "That is not a valid level" << endl;
cout << "Choose another level:";
if(!(cin >> levelChoose))
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}

Edit: numeric_limits<> is located in the limits include:

#include<limits>

a while loop for input validation c++

I think the issue here is logic. If I'm not incorrect you want to ask for input until their input is one of A a B b C c?

Putting your while loop into words your saying:
while choice is A and a
or choice is B and b
or choice is C and c
Putting it that way it obviously can't work because how can choice be A and a?

What you want is to loop until choice is one of A a B b C c

Your return also shouldn't be in the while loop, I am assuming you want to return the choice they made after it is valid?

I also added the ! (this is "not", this inverts the result of a condtion - turns true into false, and false into true) operator before all of your conditions as without this you would be looping while choice is correct which means that it would continue only after an incorrect choice is entered.

In short, this code loops through asking for an input until the user's input is one of A a B b C c, after which it returns the input they gave.

while (!(choice == 'a' || choice == 'A' || choice == 'b' || choice == 'B' || choice == 'c' || choice == 'C')) {
std::cout << "We dont offer that package. Please try again:\n ";
std::cin >> choice;
}
return choice;

In english this is while choice isn't A or a or B or b or C or c then ask for input

How to keep asking user to input until condition is satisfied in C?

I recommend that you use the following code:

#include <stdio.h>

int main( void )
{
int u1,u2,u3;

for (;;) //infinite loop, equivalent to while(true)
{
printf( "Enter 3 Numbers: " );
scanf( "%d %d %d", &u1, &u2, &u3 );

if ( u1!=u2 && u2!=u3 && u3!=u1 )
break;

printf( "Error: Condition is not satisfied!\n" );
}
}

In contrast to one of the other answers, this solution has the advantage that it only checks the condition once per loop iteration.

However, the above code (and the code of most other answers) has a serious issue: If the user enters an alphabetical letter instead of a number, the program will get stuck in an infinite loop. This is because it is not safe to call scanf without checking the return value. See the following page for more information on why it is unsafe: A beginners' guide away from scanf()

Therefore, it would be better to check the return value of scanf and to consume all characters on the remainder of the line. Consuming all leftover characters is important, because otherwise, if the user enters 6abc, then scanf will consume the 6, but leave abc on the input stream, so that the next time scanf is called (which will be in the next loop iteration), it will attempt to match abc and fail immediately without waiting for further input. This would cause an infinite loop.

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
int u1,u2,u3;
int ret;

for (;;) //infinite loop, equivalent to while(true)
{
printf( "Enter 3 Numbers: " );
if ( ( ret = scanf( "%d %d %d", &u1, &u2, &u3 ) ) != 3 )
{
int c;

//check for unrecoverable error
if ( ret == EOF )
{
fprintf( stderr, "Unrecoverable input error!\n" );
exit( EXIT_FAILURE );
}

//print error message for recoverable error
printf( "Unable to convert input!\n" );

//consume all leftover characters on the line
do
{
c = getchar();

} while ( c != EOF && c != '\n' );
}

if ( u1!=u2 && u2!=u3 && u3!=u1 )
break;

printf( "Error: Condition is not satisfied!\n" );
}
}

Keep prompting the the user until valid value provided-while loop c programming

You need scanf inside while loop to get the correct value from user by asking continuesly. Once you get correct value you don't need if condition to check correctness of value because while loop exits only after getting correct value.

#include <stdio.h>

int main(int argc, char const *argv[])
{
int num = 0;
int sum = 0;
bool flag = 0;

printf("Enter the value GREATER than 20 and LESS than 25: ");
scanf("%d", &num);

while ( num < 20 || num >25 )
{
printf("Invalid number,Enter the value GREATER than 20 and LESS than 25: ");
scanf("%d", &num);
}

while ( num <= 25 )
{
sum += num;
num++;
}

printf("sum of your number is : %d \n", sum);
return 0;
}

While loop or function for input validation

You're correct in that you should put it into a function, encapsulation is always easier in the long run (even if you're never gonna look at this program again), and it's useful to keep good practice no matter the project!

If you're not intending on making any changes to the input and it's a case of valid input or invalid input, then you could always return a bool so you could do something like

if(inputValidator() == true)
{
//perform calculations
}
else
{
//Tell the user their input is incorrect and prompt for the input again
}

proper use of scanf in a while loop to validate input

I took @4386427 idea and just added codes to cover what it missed (leading spaces and + sign), I tested it many times and it is working perfectly in all possible cases.

#include<stdio.h>
#include <ctype.h>
#include <stdlib.h>

int validate_line (char *line);

int main(){
char line[256];
int y=0;
long x;

while (y<5){
printf("Please Insert X Value\n");

if (fgets(line, sizeof(line), stdin)){//return 0 if not execute
if (validate_line(line)>0){ // check if the string contains only numbers
x =strtol(line, NULL, 10); // change the authentic string to long and assign it
printf("This is x %d" , x);
break;
}
else if (validate_line(line)==-1){printf("You Have Not Inserted Any Number!.... ");}
else {printf("Invalid Input, Insert Integers Only.... ");}
}

y++;
if (y==5){printf("NO MORE RETRIES\n\n");}
else{printf("%d Retries Left\n\n", (5-y));}

}
return 0;}

int validate_line (char *line){
int returned_value =-1;
/*first remove spaces from the entire string*/
char *p_new = line;
char *p_old = line;
while (*p_old != '\0'){// loop as long as has not reached the end of string
*p_new = *p_old; // assign the current value the *line is pointing at to p
if (*p_new != ' '){p_new++;} // check if it is not a space , if so , increment p
p_old++;// increment p_old in every loop
}
*p_new = '\0'; // add terminator

if (*line== '+' || *line== '-'){line++;} // check if the first char is (-) or (+) sign to point to next place

while (*line != '\n'){
if (!(isdigit(*line))) {return 0;} // Illegal char found , will return 0 and stop because isdigit() returns 0 if the it finds non-digit
else if (isdigit(*line)){line++; returned_value=2;}//check next place and increment returned_value for the final result and judgment next.
}

return returned_value; // it will return -1 if there is no input at all because while loop has not executed, will return >0 if successful, 0 if invalid input

}


Related Topics



Leave a reply



Submit