Thread: scanf problem

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    6

    Unhappy scanf problem

    The function is to ask the user to enter floating point numbers into an array one by one.
    Eg. x(0)=1, x(1)=2, x(2)=3....
    After a user enters the last known x(t), how do i terminate the for loop given that the user returns with a blank line.

    Code:
    #include <stdio.h>
    
    #define MAX 100
    
    float x [MAX];
    
    main()
    {
    
    register int t;
    
    for(t=0;t<MAX;t++)
    {
    
    printf("Please enter x(%d):",t);
    
    scanf("%f%c",&x[t],);
    
    printf("x(%d)=%f\n",t,x[t]);
    
    /*PROBLEM HERE: how to terminate the for loop, if a blank line is returned? using break?*/
    
    }
    
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    If scanf fails, bail from the loop using break. As an alternative you could use scanf as the loop condition, or avoid scanf altogether using and fgets/sscanf combo:
    Code:
    #include <stdio.h>
    
    #define MAX 100
    
    int main ( void )
    {
      float x[MAX];
      int   t;
    
      for ( t = 0; t < MAX; t++ ) {
        if ( scanf ( " %f", &x[t] ) != 1 )
          break;
        printf ( "x(%d)=%f\n", t, x[t] );
      }
    
      return 0;
    }
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with RPC and scanf
    By Ricardo_R5 in forum C Programming
    Replies: 11
    Last Post: 01-08-2007, 06:15 PM
  2. Problem with scanf float..
    By aydin1 in forum C Programming
    Replies: 6
    Last Post: 03-06-2005, 01:35 PM
  3. scanf problem
    By gsoft in forum C Programming
    Replies: 3
    Last Post: 01-05-2005, 12:42 AM
  4. problem with looping scanf
    By crag2804 in forum C Programming
    Replies: 6
    Last Post: 09-12-2002, 08:10 PM
  5. scanf problem
    By Flikm in forum C Programming
    Replies: 2
    Last Post: 11-05-2001, 01:48 PM