-1

I have this scanf function:

scanfResult = scanf("%s%d%d", X, &LO, &HI);

I need to write a condition that would only accept integers in the second and third place in my scanf function (in the place where %d's are) and not any letters. I could write something like that:

if (HI == 0 || LO == 0){
     printf("Wrong input.\n");
        return 0;
    }

However it than does not accepts int "0" as an input, which I want to accept. How to write a condition so that it would accept zero but not any letters? (I am a beginner)

My input is:

c 45 abc
TKN
  • 145
  • 5
  • What does your input look like? – dbush Nov 01 '19 at 19:18
  • You have to read it as a string and filter yourself. – john elemans Nov 01 '19 at 19:19
  • In a terminal after a program is running I write some string, than space, than string, than space, than integer. I want my program to accept only integers in the second and third position. – TKN Nov 01 '19 at 19:21
  • @johnelemans How to write that? (it could be easy but I am a beginner and I really do not know) – TKN Nov 01 '19 at 19:23
  • Please show an actual input you give. Are the string and two numbers on the same line or on separate lines? – Weather Vane Nov 01 '19 at 19:25
  • Not "some string" or "integer". What **exactly** is your input, and how do you know it wasn't read correctly? Please edit your question to add this information. – dbush Nov 01 '19 at 19:25
  • start by reading everything in as a string. Then examine them one by one and see if they have legal data according to your specs. If they do, you can convert strings to numbers then. – john elemans Nov 01 '19 at 19:40
  • `scanf` is difficult to use correctly, and it's difficult to use if you're trying to carefully constrain user input. Rule 1 is to check `scanf`'s return value. (In your case, if `scanfResult` is not equal to 3, something went wrong.) Then, either settle for the functionality `scanf` gives you (don't try to get fancy), or, [consider alternatives](https://stackoverflow.com/questions/58403537/what-can-i-use-to-parse-input-instead-of-scanf). – Steve Summit Nov 01 '19 at 19:52

1 Answers1

0

you can use a while loop with getchar(). put in the code for allowed alphabet. something like this

while (1)  {
   ch = getchar();
   // if ch is <enter  key > the break
   if (policyOK( ch ) ) {
      printf("%c", ch );
   } else {
       // print a beep sound or don't do anything
   }
}
Nish
  • 360
  • 2
  • 9