Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello;
I am having some little troubles finding out a way to put under my while condition the fact that my variable which is an "int" must be not a character took from an input requested before my while cycle.
While cycle is used to check if the variable wrote in input doesnt match with conditions i need for the algorithm.

What I have tried:

here is an example of code:
#include <stdio.h>

int main(){
int n;
scanf("%d", &n);
while(n<=-1 ){
printf("Incorrect. Write a positive integer.");
scanf("%d", &n);
}


return 0;
}

This is working for numbers, but if in input i write a character like "g" it loopes and i must control+c, blocking it.
Posted
Updated 11-Oct-18 1:06am
v4
Comments
#realJSOP 11-Oct-18 7:07am    
This is not a C# question. I changed the tag so it would be correctly categorized.

1 solution

You tagged this C#, but it is clearly C or C++.
However, this is quite a simple problem to resolve with a loop:
C++
int n;
while (scanf("%d", &n) == 0 || n < 0) // if no values captured, or the result is negative
{
    printf("Incorrect. Write a positive integer.");
    fseek(stdin,0,SEEK_END);
}
 
Share this answer
 
v2
Comments
Member 14015940 11-Oct-18 7:30am    
Thank you for the answer, im a very beginner.

With the new condition, if i still put a character it gives me the same problem.

"d
Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. Write a positive integer.Incorrect. "

I dont get why
Richard MacCutchan 11-Oct-18 7:56am    
Sorry, I forgot to clear the input buffer after reading a non-number. See my updated solution.
CPallini 11-Oct-18 9:11am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900