2021-10-31

Accepting multiple user inputs in C

I am writing a program in C that accepts user input in either of these formats:

  1. string, int
  2. string, int, int or float

Some examples of valid inputs:

  1. Susan 5
  2. David 10 24
  3. Sarah 6 7.5

How do I accomplish this in C?

Here is the code I have so far:

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

int main()
{
    char name[10];
    int num1;
    int num2;

    if(scanf("%s %d", name, &num1) != 2 || scanf("%s %d %d", name, &num1, &num2) != 3)
    {
            printf("Failure");
    }
    else
    {
        printf("Pass");
    }
}

This intends to print "Failure" if there is invalid user input and "Pass" if the user input is valid. The issue here is this code forces me to enter both formats in order to print "Pass." So if I input "Susan 5" I would have to input "David 10 24" in order to print "Pass" even though I have an or conditional and not an and conditional, which I don't understand. What I want is once I input "Susan 5" and hit enter, my program should be able to print "Pass."



from Recent Questions - Stack Overflow https://ift.tt/3vWGfhu
https://ift.tt/eA8V8J

No comments:

Post a Comment