Thread: input while/scanf

  1. #1
    Registered User
    Join Date
    Aug 2012
    Posts
    38

    Arrow input while/scanf

    HEY there,

    Just wrote my massive question which I lost when the page refreshed. so annoying. but in short:

    1. How do I ensure that only 3 values are inputted into the system? I thought I could do it like this: while(scanf("%d%d%d",&x,&y,&z)==3)
    doesn't seem to be working

    2. How do I allow an infinite number of inputs??? (e.g: running sum of numbers).

    3. What's wrong with my code?! need to find max of 3 values, by using function.


    Thanks guys!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int int_max_3(int, int, int);
    
    
    
    
    
    
    int
    main(int argc, char **argv) {
        
        int x, y, z;
        printf("Enter three ints: ");
        while(scanf("%d%d%d",&x,&y,&z)==3)    
        printf("x=%d y=%d z=%d", x, y, z);
        int answer = int_max_3(x, y, z);    
        printf("The answer is %d.", answer);
        
        return 0;
    }
    
    
    
    
    int
    int_max_3(int a, int b, int c) {
        int answer;
            
        if ((a>b) && (b>c))
            answer = a;
        else if ((b>a) && (b>c))
            answer = b;
        else
            answer = c;
        
        return answer;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Well, if you had better indentation, and uses braces all the time, you would see this.
    Code:
    int
    main(int argc, char **argv) {
        
        int x, y, z;
        printf("Enter three ints: ");
        while(scanf("%d%d%d",&x,&y,&z)==3) {
            printf("x=%d y=%d z=%d", x, y, z);
        }
        int answer = int_max_3(x, y, z);    
        printf("The answer is %d.", answer);
        
        return 0;
    }
    You're only printing the 3 integers when everything was read correctly.
    It only gets to the int_max_3 call when scanf FAILS to read 3 integers.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with scanf given a file as input
    By lower level in forum C Programming
    Replies: 1
    Last Post: 04-11-2011, 12:03 AM
  2. input using scanf()
    By kizyle502 in forum C Programming
    Replies: 5
    Last Post: 09-10-2009, 12:56 AM
  3. Input and Scanf
    By DAaaMan64 in forum C Programming
    Replies: 3
    Last Post: 01-14-2009, 06:56 PM
  4. Limiting scanf input
    By SMurf in forum C Programming
    Replies: 0
    Last Post: 11-21-2002, 06:39 AM
  5. help with input and scanf
    By kpw in forum C Programming
    Replies: 9
    Last Post: 08-28-2001, 08:21 PM