Click here to Skip to main content
13,799,002 members
Rate this:
 
Please Sign up or sign in to 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 11-Oct-18 1:49am
Updated 11-Oct-18 2:06am
v4
Comments
   
This is not a C# question. I changed the tag so it would be correctly categorized.

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

You tagged this C#, but it is clearly C or C++.
However, this is quite a simple problem to resolve with a loop:
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);
}
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web01 | 2.8.181207.3 | Last Updated 11 Oct 2018
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100